Javascript Best Practices

Use strict mode. It makes JavaScript a cleaner language.

Always use semicolons. Avoid the pitfalls of automatic semicolon insertion.

Always use strict equality (===) and strict inequality (!==). I recommend never deviating from this rule. I even prefer the first of the following two conditions, even though they are equivalent:

if (x !== undefined && x !== null) ... // my choice
if (x != null) ... // equivalent

Either use only spaces or only tabs for indentation, but don’t mix them.

Quoting strings: You can write string literals with either single quotes or double quotes in JavaScript. Single quotes are more common. They make it easier to work with HTML code (which normally has attribute values in double quotes).

Avoid global variables.

Brace Styles:

1TBS (One True Brace Style)
Here, a block is more closely associated with the header of its statement; it starts after it, in the same line. The bodies of control flow statements are always put in braces, even if there is only a single statement.

For example:

// One True Brace Style
function foo(x, y, z) {
   if(x){
      a();
   }else{
      b();
      c();
   }
}

The de facto standard in the JavaScript world is 1TBS. It has been inherited from Java and most style guides recommend it. One reason for that is objective. If you return an object literal, you must put the opening brace in the same line as the keyword return, like this (otherwise, automatic semicolon insertion inserts a semicolon after return, meaning that nothing is returned;

return {
   name: 'Jane'
};

Prefer Literals to Constructors:
Several literals produce objects that can also be created by constructors.
However, the latter is normally the better choice:

var obj = new Object(); // no
var obj = {}; // yes

var arr = new Array(); // no
var arr = []; // yes

var regex = new RegExp('abc'); // avoid if possible
var regex = /abc/; // yes

Don’t ever use the constructor Array to create an array with given elements.

var arr = new Array('a', 'b', 'c'); // never ever
var arr = [ 'a', 'b', 'c' ]; // yes

Leave a Reply