× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

JavaScripts Best Practices, there is always a shorter way vol.1

Emre Sakarya
Jan 13, 2017
<p>There are always many ways that take you to your target. But some of them shorter than others. Short ways are also preferable not only because it's short but also it's easy to catch and debug errors.</p> <p> </p> <p><strong>Sample issue:</strong></p> <p>You have numbers that should always have same length. And shorter numbers should be filled with "0" in front to get a pattern like 0001, 0009,0087,0123,9873 etc.</p> <p>A solution :</p> <pre><code class="language-javascript"> function fillZero(num) { if (num &lt; 10) { return '000' + num; } else if (num &lt; 100) { return '00' + num; } else if (num &lt; 1000) { return '0' + num; } else { return num; } } fillZero(9) ; // outputs 0009</code></pre> <p>Or another way:</p> <pre><code class="language-javascript"> function fillZero(num){ var len = String(num).length, fill =""; for(var i = len; i&lt;4; i++){ fill +="0" } return fill + num; } fillZero(9) ; // outputs 0009</code></pre> <p>There are also another ways to reacht to this target but how about this :</p> <pre><code class="language-javascript">('0000' + 9).slice(-4); // outputs 0009</code></pre> <p> </p> <p>Make it reusable even more let it to apply other patterns instead of filling with "0".</p> <pre><code class="language-javascript">function fillPattern(pattern,num){ return (pattern + num).slice(pattern.length * -1); } fillPattern('0000',9) ; // outputs 0009</code></pre> <p> </p> <p>This is a sample usage of slice method with minus value. </p>
comments powered by Disqus