Top 10 JavaScript Best Practices for newer

06/19/2009
1. Use === Instead of ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

"If two operands are of the same type and value, then === produces true and !== produces false." - JavaScript: The Good Parts

However, when working with == and !=, you'll run into issues when working with different types. In these cases, they'll try to coerce the values, unsuccessfully.

2. Eval = Bad

For those unfamiliar, the "eval" function gives us access to JavaScript's compiler. Essentially, we can execute a string's result by passing it as a parameter of "eval".

Not only will this decrease your script's performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!

3. Don't Use Short-Hand

Technically, you can get away with omitting most curly braces and semi-colons. Most browsers will correctly interpret the following:

view plaincopy to clipboardprint?

  1. if(someVariableExists) 
  2.    x = false
if(someVariableExists)
x = false

However, consider this:

view plaincopy to clipboardprint?

  1. if(someVariableExists) 
  2.    x = false
  3.    anotherFunctionCall(); 
if(someVariableExists)
x = false
anotherFunctionCall();

One might think that the code above would be equivalent to:

view plaincopy to clipboardprint?

  1. if(someVariableExists) { 
  2.    x = false; 
  3.    anotherFunctionCall(); 
if(someVariableExists) {
x = false;
anotherFunctionCall();
}

Unfortunately, he'd be wrong. In reality, it means:

view plaincopy to clipboardprint?

  1. if(someVariableExists) { 
  2.    x = false; 
  3. anotherFunctionCall(); 
if(someVariableExists) {
x = false;
}
anotherFunctionCall();

As you'll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs. The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic.

view plaincopy to clipboardprint?

  1. if(2 + 2 === 4) return 'nicely done'; 
if(2 + 2 === 4) return 'nicely done';
Always Consider the Future

What if, at a later date, you need to add more commands to this if statement. In order to do so, you would need to rewrite this block of code. Bottom line - tread with caution when omitting.

4. Utilize JS Lint

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it'll quickly scan for any noticeable issues and errors in your code.

"JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems."
- JSLint Documentation

Before signing off on a script, run it through JSLint just to be sure that you haven't made any mindless mistakes.

5. Place Scripts at the Bottom of Your Page

This tip has already been recommended in the previous article in this series. As it's highly appropriate though, I'll paste in the information.

Place JS at bottom

Remember -- the primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can't continue on until the entire file has been loaded. Thus, the user will have to wait longer before noticing any progress.

If you have JS files whose only purpose is to add functionality -- for example, after a button is clicked -- go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

Better

view plaincopy to clipboardprint?

  1. <p>And now you know my favorite kinds of corn. </p>
  2. <script type="text/javascript" src="path/to/file.js"></script>
  3. <script type="text/javascript" src="path/to/anotherFile.js"></script>
  4. </body>
  5. </html>
<p>And now you know my favorite kinds of corn. </p>
<script type="text/javascript" src="path/to/file.js"></script>
<script type="text/javascript" src="path/to/anotherFile.js"></script>
</body>
</html>
6. Declare Variables Outside of the For Statement

When executing lengthy "for" statements, don't make the engine work any harder than it must. For example:

Bad

view plaincopy to clipboardprint?

  1. for(var i = 0; i < someArray.length; i++) { 
  2. var container = document.getElementById('container'); 
  3.    container.innerHtml += 'my number: ' + i; 
  4.    console.log(i); 
for(var i = 0; i < someArray.length; i++) {
var container = document.getElementById('container');
container.innerHtml += 'my number: ' + i;
console.log(i);
}

Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the "container" element each time -- highly inefficient!

Better

view plaincopy to clipboardprint?

  1. var container = document.getElementById('container'); 
  2. for(var i = 0, len = someArray.length; i < len;  i++) { 
  3.    container.innerHtml += 'my number: ' + i; 
  4.    console.log(i); 
var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len;i++) {
container.innerHtml += 'my number: ' + i;
console.log(i);
}

Bonus points to the person who leaves a comment showing us how we can further improve the code block above.

7. The Fastest Way to Build a String

Don't always reach for your handy-dandy "for" statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.

view plaincopy to clipboardprint?

  1. var arr = ['item 1', 'item 2', 'item 3', ...]; 
  2. var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>'; 
var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) - this is by far the fastest method!

Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.
- James Padolsey, james.padolsey.com

8. Reduce Globals

"By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries."
- Douglas Crockford

view plaincopy to clipboardprint?

  1. var name = 'Jeffrey'; 
  2. var lastName = 'Way'; 
  3. function doSomething() {...} 
  4. console.log(name); // Jeffrey -- or window.name
var name = 'Jeffrey';
var lastName = 'Way';

function doSomething() {...}

console.log(name); // Jeffrey -- or window.name
Better

view plaincopy to clipboardprint?

  1. var DudeNameSpace = { 
  2.    name : 'Jeffrey', 
  3.    lastName : 'Way', 
  4.    doSomething : function() {...} 
  5. console.log(DudeNameSpace.name); // Jeffrey
var DudeNameSpace = {
name : 'Jeffrey',
lastName : 'Way',
doSomething : function() {...}
}
console.log(DudeNameSpace.name); // Jeffrey

Notice how we've "reduced our footprint" to just the ridiculously named "DudeNameSpace" object.

9. Comment Your Code

It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. What happens when you return to the project months later, only to find that you can't easily remember what your line of thinking was. Or, what if one of your colleagues needs to revise your code? Always, always comment important sections of your code.

view plaincopy to clipboardprint?

  1. // Cycle through array and echo out each name.
  2. for(var i = 0, len = array.length; i < len; i++) { 
  3.    console.log(array[i]); 
// Cycle through array and echo out each name. 
for(var i = 0, len = array.length; i < len; i++) {
console.log(array[i]);
}
10. Embrace Progressive Enhancement

Always compensate for when JavaScript is disabled. It might be tempting to think, "The majority of my viewers have JavaScript enabled, so I won't worry about it." However, this would be a huge mistake.

Have you taken a moment to view your beautiful slider with JavaScript turned off? (Download the Web Developer Toolbar for an easy way to do so.) It might break your site completely. As a rule of thumb, design your site assuming that JavaScript will be disabled. Then, once you've done so, begin to progressively enhance your layout!

Posted in: SEO-Webmaster| Tags: Type Javascript Best Pracitce Eval js Function value quot blockquote practice coerce equality

Hot Posts

Latest posts

Tags

Others

Sponsors

asp.net interview questions