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

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

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 a file path as string and you would need to check it whether it is a "html" file from it's extension.</p> <p>A solution :</p> <pre><code class="language-javascript">function isHTML(path){ return path.indexOf('.html')&gt;0 ; } isHTML('foo/bar/index.html'); // returns "true"</code></pre> <p>But this also returns <strong>true </strong>although it shouldn't:</p> <pre><code class="language-javascript">isHTML('foo/bar.html/main.js'); // returns "true" </code></pre> <p>This a little bit better solution :</p> <pre><code class="language-javascript">function isHTML(path) { return path.indexOf('.html') == path.length - 5; } isHTML('foo/bar/index.html'); // returns "true" isHTML('foo/bar.html/main.js'); // returns "false"</code></pre> <p>But how about this:</p> <pre><code class="language-javascript"> function isHTML(fileType,path) { return path.slice(-1 * fileType.length) == fileType; } isHTML('.html','foo/bar/index.html'); // returns "true" isHTML('.html','foo/bar.html/main.js'); // returns "false"</code></pre> <p> </p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus