JavaScript Coding Standards and Guidelines

This is the current set of coding standards and guidelines I use when I’m coding in the JavaScript language.
I thought it would be good to share so others could get use out of them also, and maybe start a discussion as to amendments / changes they see that could be useful?

Naming Conventions

Names should be formed from the 26 upper and lower case letters (A .. Z, a .. z), the 10 digits (0 .. 9), and _ (underbar).
Avoid use of international characters because they may not read well or be understood everywhere.
Do not use $ (dollar sign) or \ (backslash) in names.

I think jQuery would have to be an exception to this

Do not use _ (underbar) as the first character of a name.
It is sometimes used to indicate privacy, but it does not actually provide privacy.
If privacy is important, use the forms that provide private members.

Most variables and functions should start with a lower case letter.

Constructor functions which must be used with the new prefix should start with a capital letter.
JavaScript issues neither a compile-time warning nor a run-time warning if a required new is omitted.
Bad things can happen if new is not used, so the capitalization convention is the only defence we have.

Global variables should be in all caps.
JavaScript does not have macros or constants, so there isn’t much point in using all caps to signify features that JavaScript doesn’t have.
Same with Enum names. There is no native ability to create constant variables. Although… you can create read-only properties.
With the advent of ES5 we now have a couple of well known techniques to enforce that our property values can not be altered once initialised.

When you define a property using one of the ES5 techniques, (1) when you set the writable property attribute to false the value of the value attribute can no longer be altered. (2) Using an accessor property with only a get function

var objWithMultipleProperties;
var objWithMultiplePropertiesDescriptor;

objWithMultipleProperties = Object.defineProperties({}, {
   x: { value: 1, writable: true, enumerable:true, configurable:true }, // Change writable to false enables read-only semantics.
   y: { value: 1, writable: true, enumerable:true, configurable:true }, // Change writable to false enables read-only semantics.
   r: {
      get: function() {
         return Math.sqrt(this.x*this.x + this.y*this.y)
      },
      enumerable:true,
      configurable:true
   }
});

objWithMultiplePropertiesDescriptor = Object.getOwnPropertyDescriptor(objWithMultipleProperties, 'r');
// objWithMultiplePropertiesDescriptor {
//    configurable: true,
//    enumerable: true,
//    get: function () {
//       // other members in here
//    },
//    set: undefined,
//   // ...
// }

See here for complete coverage of property attributes.

Coding Style

Commenting

Use comments where needed.

If the script needs commenting due to complexity, consider revising before commenting.
Comments easily rot (can be left behind after future code changes).
It is important that comments be kept up-to-date. Erroneous comments can make programs even harder to read and understand.
In this case they cause more damage than they originally gave benefit.
Comments should be well-written and clear, just like the code they are annotating.

Make comments meaningful. Focus on what is not immediately visible. Don’t waste the reader’s time with stuff like

i = 0; // Set i to zero.

Comment Style

Block comments are not safe for
commenting out blocks of code. For example:

/*
var rm_a = /a*/.match(s);
*/

causes a syntax error. So, it is recommended that /* */ comments be avoided and //
comments be used instead.

Don’t use HTML comments in script blocks. In the ancient days of javascript (1995), some browsers like Netscape 1.0 didn’t have any support or knowledge of the script tag. So when javascript was first released, a technique was needed to hide the code from older browsers so they wouldn’t show it as text in the page. The ‘hack’ was to use HTML comments within the script block to hide the code.

<script language="javascript">
<!--
   // code here
   //-->
</script>

No browsers in common use today are ignorant of the <script> tag, so hiding of javascript source is no longer necessary. Thanks Matt Kruse for re-iterating this.

File Organization

JavaScript programs should be stored in and delivered as .js files.

  • JavaScript should not be in HTML
  • JavaScript should not be in CSS
  • CSS should not be in JavaScript
  • HTML should not be in JavaScript

Code in HTML adds significantly to page weight with no opportunity for mitigation by caching and compression. There are many other reasons to keep the UI layers separate.

<script src=filename.js>; tags should be placed as late in the body as possible.
This reduces the effects of delays imposed by script loading on other page components.

There is no need to use the language or type attributes. It is the server, not the script tag, that determines the MIME type.

Formatting

Bracing

Use same line opening brace.
Brace positioning is more or less a holy war without any right answer — except in JavaScript, where same-line braces are right and you should always use them. Here’s why:

return
{
  ok: false;
};

return {
  ok: true;
};

What’s the difference between these two snippets? Well, in the first one, you silently get something completely different than what you wanted.
The lone return gets mangled by the semicolon insertion process and becomes return; and returns nothing.
The rest of the code becomes a plain old block statement, with ok: becoming a label (of all things)! Having a label there might make sense in C, where you can goto, but in JavaScript, it makes no sense in this context.
And what happens to false? it gets evaluated and completely ignored.
Finally, the trailing semicolon — what about that?
Do we at least get a syntax error there? Nope: empty statement, like in C.

Spacing

Blank lines improve readability by setting off sections of code that are logically related.

Blank spaces should be used in the following circumstances:

  • A keyword followed by ( (left parenthesis) should be separated by a space.
    while (true) {
    
  • A blank space should not be used between a function value and its ( (left parenthesis). This helps to distinguish between keywords and function invocations.
  • All binary operators except . (period) and ( (left parenthesis) and [ (left bracket) should be separated from their operands by a space.
  • No space should separate a unary operator and its operand except when the operator is a word such as typeof.
  • Each ; (semicolon) in the control part of a for statement should be followed with a space.
  • Whitespace should follow every , (comma).

Tabs and Indenting

The unit of indentation is three spaces.
Use of tabs should be avoided because (as of this writing in the 21st Century) there still is not a standard for the placement of tab stops.
The use of spaces can produce a larger file size, but the size is not significant over local networks, and the difference is eliminated by minification.

Line Length

Avoid lines longer than 80 characters. When a statement will not fit on a single line, it may be necessary to break it.
Place the break after an operator, ideally after a comma.
A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion.
The next line should be indented six spaces.

Language Usage

Access To Members

In JavaScript we don’t have access modifiers like we do in classical languages.

In saying that, we can and should still control the accessibility of our members, and keep as much of our objects information secret to outsiders.
We can apply public, private and Privileged access.

public

Members created in the Constructor using the dot notation

function Container(param) {
    this.member = param;
}

So, if we construct a new object

var myContainer = new Container('abc');

then myContainer.member contains 'abc'.

In the prototype we can add a public method.
To add a public method to all objects made by a constructor, add a function to the constructor’s prototype:

Container.prototype.stamp = function (string) {
    return this.member + string;
}

We can then invoke the method

myContainer.stamp('def')

which produces 'abcdef'.

private

Ordinary vars and parameters of the constructor becomes the private members

function Container(param) {
    this.member = param;
    var secret = 3;
    var that = this;
}

param, secret, and that are private member variables.
They are not accessible to the outside.
They are not even accessible to the objects own public methods.

They are accessible to private methods
Private methods are inner functions of the constructor.

function Container(param) {

    this.member = param; // param is private, member is public
    var secret = 3;      // secret is private
    var that = this;     // that is private
    function dec() {     // dec is private
        var innerFunction = function () {
            that.value = someCrazyValue;  // when dec is called, value will be a member of the newly constructed Container instance.
        };

        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }
}

A method (which is a function that belongs to an object) cannot employ an inner function to help it do its work because the inner function does not
share the method’s access to the object as its this is bound to the global object. This was a mistake in the design of the language.
Had the language been designed correctly, when the inner function is invoked, this would still be bound to the this variable of the outer function.
The work around for this is to define a variable and assign it the value of this.
By convention, the name of that variable I use is that.

  • Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.
privileged

A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside. It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.

Privileged methods are assigned with this within the constructor.

function Container(param) {

    this.member = param;
    var secret = 3;
    var that = this;

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.service = function () { // prefix with this to assign a function to be a privileged method
        if (dec()) {
            return that.member;
        } else {
            return null;
        }
    };
}

service is a privileged method. Calling myContainer.service() will return 'abc' the first three times it is called. After that, it will return null. service calls the private dec method which accesses the private secret variable. service is available to other objects and methods, but it does not allow direct access to the private members.

eval is Evil

The eval function is the most misused feature of JavaScript. Avoid it.
eval has aliases. Do not use the Function constructor. Do not pass strings to setTimeout or setInterval.

Global Abatement

JavaScript makes it easy to define global variables that can hold all of the assets of your application.
Unfortunately, global variables weaken the resiliency of programs and should be avoided.

One way to minimize the use of global variables is to create a single global variable
for your application:

var KimsGlobal = {};

That variable then becomes the container for your application:

KimsGlobal.Calculate = {
    calculatorOutPutArray: [
    $('.step1i1'),
    $('.step1i2'),
    $('.step1r1'),
    ...
    ],
    jQueryObjectCounter: 0,
    jQueryDOMElementCounter: 0
    ...
};

KimsGlobal.NavigateCalculator = {
    currentStepId: stepId,
    step: 'step' + stepId,
    stepSelector: = '#' + step,
    ...
};

By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries.
Your program also becomes easier to read because it is obvious that KimsGlobal.Calculate refers to a top-level structure.

Using closure for information hiding is another effective global abatement technique.

var digit_name = (function() {
  var names = ['zero', 'one', 'two', ...];
  return function (n) {
    return names[n];
  };
})();

Using the Module patterns explains this in detail.

Scoping

JavaScript scoping is different to classical languages, and can take some getting used to for programmers used to languages such as C, C++, C#, Java.
Classical languages like the before mentioned have block scope.
JavaScript has function scope. Although ES6 is bringing in block scoping with the let keyword.

In the following example “10” will be alerted.
var foo = 1; // foo is defined in global scope.
function bar() {
    if (!foo) { // The foo variable of the bar scope has been hoisted directly above this if statement, but the assignment has not. So it is unassigned (undefined).
        var foo = 10;
    }
    alert(foo);
}
bar();
In the following example “1” will be alerted.
var a = 1;
function b() {
    a = 10;
    return;
    function a() {}
}
b();
alert(a);
In the following example Firebug will show 1, 2, 2.
var x = 1;
console.log(x); // 1
if (true) {
    var x = 2;
    console.log(x); // 2
}
console.log(x); // 2

In JavaScript, blocks such as if statements, do not create new scope. Only functions create new scope.

There is a workaround though 😉
JavaScript has Closure.
If you need to create a temporary scope within a function, do the following.

function foo() {
    var x = 1;
    if (x) {
        (function () {
            var x = 2;
            // some other code
        }());
    }
    // x is still 1.
}

Line 3: begins a closure
Line 6: the closure invokes itself with ()

Hoisting

Terminology

function declaration or function statement are the same thing.
function expression or variable declaration with function assignment are the same thing.

A function statement looks like the following:

function foo( ) {}

A function expression looks like the following:

var foo = function foo( ) {};

A function expression must not start with the word “function”.

//anonymous function expression
var a = function () {
    return 3;
}

//named function expression
var a = function bar() {
    return 3;
}

//self invoking named function expression. This is also a closure
(function sayHello() {
    alert('hello!');
})();

//self invoking anonymous function expression. This is also a closure
(function ( ) {
    var hidden_variable;
    // This function can have some impact on
    // the environment, but introduces no new
    // global variables.
}() );

In JavaScript, a name enters a scope in one of four basic ways:

  1. Language-defined: All scopes are, by default, given the names this and arguments.
  2. Formal parameters: Functions can have named formal parameters, which are scoped to the body of that function.
  3. Function declarations: These are of the form function foo() {}.
  4. Variable declarations: These take the form var foo;.

Function declarations and variable declarations are always hoisted invisibly to the top of their containing scope by the JavaScript interpreter.
Function parameters and language-defined names are, obviously, already there. This means that code like this:

function foo() {
    bar();
    var x = 1;
}

Is actually interpreted like this:

function foo() {
    var x;
    bar();
    x = 1;
}

It turns out that it doesn’t matter whether the line that contains the declaration would ever be executed. The following two functions are equivalent:

function foo() {
    if (false) {
        var x = 1;
    }
    return;
    var y = 1;
}
function foo() {
    var x, y;
    if (false) {
        x = 1;
    }
    return;
    y = 1;
}

The assignment portion of the declaration is not hoisted.
Only the identifier is hoisted.
This is not the case with function declarations, where the entire function body will be hoisted as well,
but remember that there are two normal ways to declare functions. Consider the following JavaScript:

function test() {
    foo(); // TypeError 'foo is not a function'
    bar(); // 'this will run!'
    var foo = function () { // function expression assigned to local variable 'foo'
        alert('this won't run!');
    }
    function bar() { // function declaration, given the name 'bar'
        alert('this will run!');
    }
}
test();

In this case, only the function declaration has its body hoisted to the top. The name ‘foo’ is hoisted, but the body is left behind, to be assigned during execution.

Name Resolution Order

The most important special case to keep in mind is name resolution order. Remember that there are four ways for names to enter a given scope. The order I listed them above is the order they are resolved in. In general, if a name has already been defined, it is never overridden by another property of the same name. This means that a function declaration takes priority over a variable declaration. This does not mean that an assignment to that name will not work, just that the declaration portion will be ignored. There are a few exceptions:

  • The built-in name arguments behaves oddly. It seems to be declared following the formal parameters, but before function declarations. This means that a formal parameter with the name arguments will take precedence over the built-in, even if it is undefined. This is a bad feature. Don’t use the name arguments as a formal parameter.
  • Trying to use the name this as an identifier anywhere will cause a Syntax Error. This is a good feature.
  • If multiple formal parameters have the same name, the one occurring latest in the list will take precedence, even if it is undefined.

Additional hoisting examples on my blog

Now that you understand scoping and hoisting, what does that mean for coding in JavaScript?
The most important thing is to always declare your variables with var statements.
Declare your variables at the top of the scope (as already mentioned JavaScript only has function scope). See the Variable Declarations section.
If you force yourself to do this, you will never have hoisting-related confusion.
However, doing this can make it hard to keep track of which variables have actually been declared in the current scope.
I recommend using strict mode which will inform you if you have tried to use a variable without declaring it with var. If you’ve done all of this, your code should look something like this:

function foo(a, b, c) {
    'use strict';
    var x = 1;
    var bar;
    var baz = 'something';
    // other non hoistable code here
}

Inheritance

Always prefer Prototypal inheritance to Pseudo classical.

There are quite a few reasons why we shouldn’t use Pseudo classical inheritance in JavaScript.
JavaScript The Good Parts explains why.

In a purely prototypal pattern, we dispense with classes.
We focus instead on the objects.
Prototypal inheritance is conceptually simpler than classical inheritance.

I’ll show you three examples of prototypal inheritance, and explain the flaws and why the third attempt is the better way.

Example 1
function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

The object function takes an existing object as a parameter and returns an empty new object that inherits from the old one.
The problem with the object function is that it is global, and globals are clearly problematic.

Example 2
Object.prototype.begetObject = function () {
    function F() {}
    F.prototype = this;
    return new F();
};

newObject = oldObject.begetObject();

The problem with Object.prototype.begetObject is that it trips up incompetent programs, and it can produce unexpected results when begetObject is overridden.

Example 3
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
newObject = Object.create(oldObject);

Example 3 overcomes the problems with the previous prototypical examples.
This is how Object.create works in ES5

New

Use {} instead of new Object(). Use [] instead of new Array(). There are instances where using new allows compiler optimisations to be performed. Learn what happens when you use new in different scenarios and test.

Operators

Plus Minus

Be careful to not follow a + with + or ++. This pattern can be confusing. Insert parens between them to make your intention clear.

total = subtotal + +myInput.value;

is better written as

total = subtotal + (+myInput.value);

so that the + + is not misread as ++.

Equality
By default use the === operator rather than the == operator.
By default use the !== operator rather than the != operator.

JavaScript has two sets of equality operators: === and !==, and their (as Douglas Crockford puts it) evil twins == and
!=. The === and !== ones work the way you would expect. If the two operands are of the
same type and have the same value, then === produces true and !== produces false.
The other ones do the right thing when the operands are of the same type, but if they
are of different types, they attempt to coerce the values.
Make sure this is what you need rather than just blindly using the shorter form.
These are some of the interesting cases:

'' == '0'          // false
0 == ''            // true
0 == '0'           // true
false == 'false'   // false
false == '0'       // true
false == undefined // false
false == null      // false
null == undefined  // true
' \t\r\n ' == 0    // true

Patterns

Module

Module presents an interface but hides its state and implementation.
Takes advantage of function scope and closure to create relationships that are binding and private.
Eliminate the use of global variables. It promotes information hiding and other good design practices.

Global Import

JavaScript has a feature known as implied globals.
Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name.
If none is found, that variable is assumed to be global.
If it’s used in an assignment, the global is created if it doesn’t already exist.
This means that using or creating global variables in an anonymous closure is easy.
Unfortunately, this leads to hard-to-manage code, as it’s not obvious (to humans) which variables are global in a given file.

Luckily, our anonymous function provides an easy alternative.
By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals.

(function ($, YAHOO) {
    // now have access to globals jQuery (as $) and YAHOO in this code
}(jQuery, YAHOO));
Module Export

Sometimes you don’t just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function’s return value.

var MODULE = (function () {
    var my = {},
        privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

Notice that we’ve declared a global module named MODULE, with two public properties:
a method named MODULE.moduleMethodand a variable named MODULE.moduleProperty.
In addition, it maintains private internal state using the closure of the anonymous function.
Also, we can easily import needed globals, using the pattern we learned above.

Augmentation

One limitation of the module pattern so far is that the entire module must be in one file.
Anyone who has worked in a large code-base understands the value of splitting among multiple files.
Luckily, we have a nice solution to augment modules.
First, we import the module, then we add properties, then we export it.
Here’s an example, augmenting our MODULE from above:

var MODULE = (function (my) {
    my.anotherMethod = function () {
        // added method...
    };

    return my;
}(MODULE));

Use the var keyword again.
After this code has run, our module will have gained a new public method named MODULE.anotherMethod.
This augmentation file will also maintain its own private internal state and imports.

Loose Augmentation

While our example above requires our initial module creation to be first, and the augmentation to happen second, that isn’t always necessary.
One of the best things a JavaScript application can do for performance is to load scripts asynchronously.
We can create flexible multi-part modules that can load themselves in any order with loose augmentation.
Each file should have the following structure:

var MODULE = (function (my) {
    // add capabilities...

    return my;
}(MODULE || {}));

The import will create the module if it doesn’t already exist.
This means you can use a library like require.js and load all of your module files in parallel, without needing to block.
preferably not more than 2 to 3 at a time, else performance will degrade

Tight Augmentation

While loose augmentation is great, it does place some limitations on your module.
Most importantly, you cannot override module properties safely.
You also cannot use module properties from other files during initialization (but you can at run-time after intialization).
Tight augmentation implies a set loading order, but allows overrides.
Here is a simple example (augmenting our original MODULE):

var MODULE = (function (my) {
    var old_moduleMethod = my.moduleMethod;

    my.moduleMethod = function () {
        // method override, has access to old through old_moduleMethod...
    };

    return my;
}(MODULE));

Here we’ve overridden MODULE.moduleMethod, but maintain a reference to the original method, if needed.

Cloning and Inheritance
var MODULE_TWO = (function (old) {
    var my = {},
    var key;

    for (key in old) {
        if (old.hasOwnProperty(key)) {
            my[key] = old[key];
        }
    }

    var super_moduleMethod = old.moduleMethod;
    my.moduleMethod = function () {
        // override method on the clone, access to super through super_moduleMethod
    };

    return my;
}(MODULE));

This pattern is perhaps the least flexible option. It does allow some neat compositions, but that comes at the expense of flexibility.
As I’ve written it, properties which are objects or functions will not be duplicated, they will exist as one object with two references.
Changing one will change the other.
This could be fixed for objects with a recursive cloning process, but probably cannot be fixed for functions, except perhaps with eval.

Sub-modules
MODULE.sub = (function () {
    var my = {};
    // ...

    return my;
}());

Statements

Simple Statements

Each line should contain at most one statement.
Put a ; (semicolon) at the end of every simple statement.
Note that an assignment statement which is assigning a function literal or object literal is still an assignment statement and must end with a semicolon.

JavaScript allows any expression to be used as a statement.
This can mask some errors, particularly in the presence of semicolon insertion.
The only expressions that should be used as statements are assignments and invocations.

Compound Statements

Compound statements are statements that contain lists of statements enclosed in { } (curly braces).

  • The enclosed statements should be indented four more spaces.
  • The { (left curly brace) should be at the end of the line that begins the compound statement.
  • The } (right curly brace) should begin a line and be indented to align with the beginning of the line containing the matching { (left curly brace).
  • Braces should be used around all statements, even single statements, when they are part of a control structure, such as an if or for statement. This makes it easier to add statements without accidentally introducing bugs.
Labels
Say no to labelling Statement labels are optional. Only these statements should be labelled: while, do, for, switch. Or better still don’t use labelling.
return Statement

A return statement with a value should not use ( ) (parentheses) around the value.
The return value expression must start on the same line as the return keyword in order to avoid semicolon insertion.

if Statement

The if class of statements should have the following form:

if (condition) {
    statements
}

if (condition) {
    statements
} else {
    statements
}

if (condition) {
    statements
} else if (condition) {
    statements
} else {
    statements
}

Avoid doing assignments in the condition part of if and while statements.

Is

if (a = b) {

a correct statement? Or was

if (a === b) {

intended? Avoid constructs that cannot easily be determined to be correct.

Also see the Equality section

for Statement

A for class of statements should have the following form:

for (initialisation; condition; update) {
    statements
}

for (variable in object) {
    if (filter) {
        statements
    }
}

The first form should be used with arrays and with loops of a predetermined number of iterations.

The second form should be used with objects.
Be aware that members that are added to the prototype of the object will be included in the enumeration.
It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object:

for (variable in object) {
    if (object.hasOwnProperty(variable)) {
        statements
    }
}
while Statement

A while statement should have the following form:

while (condition) {
    statements
}
do Statement

A do statement should have the following form:

do {
    statements
} while (condition);

Unlike the other compound statements, the do statement always ends with a ; (semicolon).

switch Statement

A switch statement should have the following form:

switch (expression) {
case expression:
    statements
default:
    statements
}

Each case is aligned with the switch. This avoids over-indentation.
Each group of statements (except the default) should end with break, return, or throw. Do not fall through.

Or better, use the following form from Angus Crolls blog post

Procedural way to do the construct

var whatToBring;
switch(weather) {
    case 'Sunny':
        whatToBring = 'Sunscreen and hat';
        break;
    case 'Rain':
        whatToBring  ='Umbrella and boots';
        break;
    case 'Cold':
        whatToBring = 'Scarf and Gloves';
        break;
    default : whatToBring = 'Play it by ear';
}

OO way to do the construct

var whatToBring = {
    'Sunny' : 'Sunscreen and hat',
    'Rain' : 'Umbrella and boots',
    'Cold' : 'Scarf and Gloves',
    'Default' : 'Play it by ear'
}

var gear = whatToBring[weather] || whatToBring['Default'];
try Statement

The try class of statements should have the following form:

try {
    statements
} catch (variable) {
    statements
}

try {
    statements
} catch (variable) {
    statements
} finally {
    statements
}
continue Statement

Avoid use of the continue statement. It tends to obscure the control flow of the function.

with Statement

Why it shouldn’t be used.

Why it should be used.

with statement Both points are valid. Understand how it works before you use it. It aint going to work with strict mode anyway, for good reason IMHO.

Function Declarations

  • All functions should be declared before they are used.
  • Inner functions should follow the var statement. This helps make it clear what variables are included in its scope.
  • There should be no space between the name of a function and the ( (left parenthesis) of its parameter list.
  • There should be one space between the ) (right parenthesis) and the { (left curly brace) that begins the statement body.
    The body itself is indented four spaces.
    The } (right curly brace) is aligned with the line containing the beginning of the declaration of the function.

This convention works well with JavaScript because in JavaScript, functions and object literals can be placed anywhere that an expression is allowed.
It provides the best readability with inline functions and complex structures.

function getElementsByClassName(className) {
    var results = [];
    walkTheDOM(document.body, function (node) {
        var a; // array of class names
        var c = node.className; // the node's classname
        var i; // loop counter

// If the node has a class name, then split it into a list of simple names.
// If any of them match the requested name, then append the node to the set of results.

        if (c) {
            a = c.split(' ');
            for (i = 0; i < a.length; i += 1) {
                if (ai === className) {
                    results.push(node);
                    break;
                }
            }
        }
    });
    return results;
}

If a function literal is anonymous, there should be one space between the word function and the ( (left parenthesis).
If the space is omitted, then it can appear that the function’s name is function, which is an incorrect reading.

div.onclick = function (e) {
   return false;
};

that = {
    method: function () {
         return this.datum;
    },
    datum: 0
};

When a function is to be invoked immediately,
the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

var collection = (function () {
    var keys = [], values = [];

    return {
    get: function (key) {
        var at = keys.indexOf(key);
        if (at >= 0) {
             return values[at];
        }
    },
    set: function (key, value) {
        var at = keys.indexOf(key);
        if (at < 0) {
            at = keys.length;
        }
        keysat = key;
        valuesat = value;
    },
    remove: function (key) {
        var at = keys.indexOf(key);
        if (at >= 0) {
            keys.splice(at, 1);
            values.splice(at, 1); }
        }
    };
}());

Variable Declarations

All variables should be declared before used.
JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that become implied globals.
If you get into the habit of using strict mode, you’ll get pulled up on this anyway.
Implied global variables should never be used.

The var statements should be the first statements in the function body.

It is preferred that each variable be given its own line. They should be listed in alphabetical order.

var currentSelectedTableEntry;
var indentationlevel;
var sizeOfTable;

JavaScript does not have block scope (see Scope section), so defining variables in blocks can confuse programmers who are experienced with other C family languages.

  • Define all variables at the top of the function.
  • Use of global variables should be minimized.
  • Implied global variables should never be used.

References

http://javascript.crockford.com/code.html

http://www.webreference.com/programming/javascript/prototypal_inheritance/

http://javascript.crockford.com/prototypal.html

http://www.crockford.com/javascript/inheritance.html

http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Tags:

14 Responses to “JavaScript Coding Standards and Guidelines”

  1. Scoping & Hoisting in JavaScript « Binarymist Says:

    […] of which variables have actually been declared in the current scope. I generally like to follow these coding standards with […]

  2. David Clarke (@zebratale) Says:

    With respect to naming conventions, I find it useful to prefix a variable name with a $ when it contains a jQuery object and this is a common jQuery idiom.

  3. binarymist Says:

    Bruno Almeida left a comment on the Linkedin Coders group.
    I thought it worth adding, as I addressed his concerns.

    “JavaScript does not have macros or constants, so there isn’t much point in using all caps to signify features that JavaScript doesn’t have.”
    We better already prepare for ECMAScript 6.0. So it’s ok to use const, let and var and use full CAPS for const.

    ” tags should be placed as late in the body as possible.”
    Just use defer or async (depending on the objective).
    The one that is really reliable is async.
    Actually I made intensive tests on this for an open-source project I’m working on, some months ago on Firefox, Opera, Chrome, IE8, IE9 and IE10. The results show that except for IE8 and IE9, the best way is definitely to place in the , before any tags for CSS, with @async or @defer, depending on the objective. If you really want it to show ok also to IE8 and IE9, just use the conditional HTML tags that MS made for IE and place the tags both in the and the end of the body.

    Also, careful with what you write. The current stable standard is HTML4.1 and “” is not valid HTML4 (only HTML5) (this is just a headsup).

    “Tabs and Indenting”
    I use and always used tabs for indenting. There’s no standard about tab stops, true, but is there a standard for spaces? Is that 4 spaces correct? Why not use tabs and read the file with tabs as 4 spaces? I still wanted to know about that.

    “Avoid lines longer than 80 characters”
    Why? What’s the problem of having a line with 81 characters?
    I have already made code with 120, or so, characters that actually was more readable than placing it in two lines. Actually, to stay readable I would have to have it in 4 lines (believe it or not).

    “By convention, the name of that variable I use is that.”
    I use “me”, I have already read code that uses “_this”. Anyway both seem ok.

    That privileged method… I only remember that js had public methods.
    Those functions declared inside the constructor… Why not making it an anonymous function and storing it in a variable? If you do that they do not belong to the window object but to the variable in which you store it, instead.
    You are introducing here concepts that the language itself does not know what it is. You may create, later, problems related to it.

    “eval is Evil”
    I agree, but better state why, not just saying that it is evil. You may just use a link to a place where it explains why is it evil.

    “Scoping”
    You should mention the “let” too. It is already defined, at least, in the latest ECMAScript spec.

    In “Loose Augmentation”
    Are you talking about the script@async?

    “if Statement”
    In the part:
    “if (a = b) {”
    If one wants to use like that, then he should use:
    ‘if ((a = b)) {‘
    Instead to show that he really meant to use like that. Browsers like firefox warns the developer if he uses
    “if (a = b) {“,
    so better if we don’t.

    How about the if … in …, huh?

    That’s all I have to do. With the rest, I never used such stuff or I agree with you.
    Good luck and have fun.

    • binarymist Says:

      We’ve been using var from the beginning.
      const and let go without saying.
      My thoughts are similar to Nicholas C Zakas http://www.nczonline.net/blog/2012/07/24/thoughts-on-ecmascript-6-and-new-syntax/
      const just defines a read only property (syntactic sugar for Object.defineProperty).
      The writable property of the properties property descriptor is set to false.
      So they are actually read only rather than constant, but effectively constant once initialised.
      Refer to my post on JavaScript Properties.
      Agree with preparing for ES6, but many organisations will not be able to start using the new features until their clients have moved from older browsers.
      In reality, that often takes years.

      The defer or async attributes of the script tag may work if you can guarantee all your customers are using compliant browsers.
      Often they are not.
      defer has been around longer than async.
      For example IE 10 is the first version to support async. So we can’t rely on support being present.
      You mention using the HTML conditional comment tags.
      This means you loose the benefit of asynchronous loading in IE.
      Personally I’d prefer to have any benefits in all my supported browsers.
      That’s why I’d look at using something like headjs or requirejs for this scenario.
      http://headjs.com/
      http://requirejs.org/
      Compare traditional script loading with headjs:
      http://headjs.com/test/script.html vs http://headjs.com/test/headjs.html
      Loading scripts asynchronously don’t block.
      There are lots of ways to retrieve resources asynchronously without relying specifically on HTML features being supported.
      defer and async have their place, but they lack a nice abstraction layer, are a course grained approach, and don’t work in all browsers.
      Here’s some more info on some async and defer tests: http://www.stevefenton.co.uk/Content/Blog/Date/201203/Blog/HTML-Async-And-Defer-Attributes/

      Re: Tabs and Indenting.
      A space is always a space.
      A tab can be a tab or any number of spaces, depending on how you’ve got your editor setup.
      The idea is uniformity.
      Set your tab key to produce 3 or 4 spaces (what ever you decide).
      That way your indentation will be consistent.
      So yes, read the file as 4 spaces as you say.

      Re: line length.
      Again this is about uniformity.
      If you have a developer on the team that has a wider screen resolution than everyone else and insists on using as much width as possible, how is this going to affect the rest of the team?
      The line may need to be drawn somewhere. I drew it.
      You are welcome to decide on a different length or none at all if you have a team of developers that just think about these things and don’t push the line length limit consistently and annoy the rest of the team.
      Conventions and guidelines are to be decided by the team writing the code.
      The rules my team agree on won’t be the same rules that every other team agrees on.
      I would remove this if enough other developers feel the same way as you.

      Re: By convention, the name of that variable I use is that.
      Yeah, I’ve worked on teams that use self.
      For example knockoutjs uses self.

      Re: That privileged method.
      “I only remember that js had public methods”.
      Technically all object members are public.
      You can create functions that are enclosed within the constructors scope. These are not visible outside of the object that the constructor returns.
      Technically they are not members of the returned object, but they belong to the returned objects scope, so they act as private members. Welcome to closure which I’ve posted on here.
      “Why not making it an anonymous function and storing it in a variable? If you do that they do not belong to the window object but to the variable in which you store it, instead.”
      In my example, if Container is invoked as a constructor, that’s using the new prefix, a new object is created with a hidden link to the value of the functions prototype member, the this is then bound to that new object rather than the global object or window as you’ve mentioned.
      So, if you invoke the constructor as it’s supposed to be invoked, this doesn’t reference the global object but the object that it’s supposed to.
      I’ve explained this quite a few times in my blog.
      Try and familiarise your self with the JavaScript invocation patterns and how to go about using constructors in JavaScript.
      It sounds like you’re using a constructor as a function (without the new prefix)?
      No new concepts here, just tried, tested and confirmed patterns.

      Re: “eval is Evil”
      My intention of this post was not to create a book, but rather standards and guidelines.
      Explanations can be found in many places which I think are better suited to a discussion specifically targeting the why/why not.
      The longer the standards and guidelines are, the less likely they are to be read in full.

      Re: let.
      As discussed above.
      let is part of ES6 or harmony.
      I haven’t written any production code for ES6 as no legacy browsers support at this stage.
      Plenty of info around the net on let though for those looking into ES6.

      Re: “Loose Augmentation”
      No, I’m talking about augmenting JavaScript objects using JavaScript.
      As I’ve mentioned above, there are many ways to load JavaScript.
      Research as many as you have time for and choose the option that works the best for you.

      Re: “if Statement”
      I’m not sure why you are double bracketing?

      Thanks for your comments.

      • brunoais Says:

        “My thoughts are similar to Nicholas C Zakas http://www.nczonline.net/blog/2012/07/24/thoughts-on-ecmascript-6-and-new-syntax/
        In a general view, me too. I think that there’s new syntax that does not sound like javascript anymore. I don’t like that. I like the explicit “function” name. In java it’s not better: “public static volatile final int name = value;”
        So what’s the problem with how much one writes if it’s more explicit and easier to read?
        I still wonder… Ppl are getting exaggerated lazy bums.

        In my PC,
        “SCRIPT SRC before 1682 ms”
        “SCRIPT SRC via HeadJS 2375ms”
        Is it an advantage in modern browsers? I wonder…
        Anyway, I still don’t have a real life example of my works. I only did stuff and simulate usage (just like that headjs example). I still need to make my own complete project and test for real which one really sounds better in a real life page with many images, scripts CSS and other stuff. If some1 can get me a real good real life example page that can work as an “average” page, please do. I’d be glad to test it. For now, I only have my localhost server, which is not that good as a test due to communication times. Either way, I do try to mimic connection problems with a SSL (SSLanguage) but, in the end, it’s not the same.
        Either way… I still think that the way I think it can be done and it REALLY compensates when under slow internet speeds.

        “Re: Tabs and Indenting.”
        I still prefer how tabs work. If your screen is wider, you can use bigger tabs, if you want. If the screen is less wide, you can squeeze those tabs to becomes smaller. No code change. Also it’s easier to adjust to align stuff (but that also requires a standardization of tab size (usually (and I prefer) 4 spaces))

        “Re: line length.”
        I still think that 80 is just because of the paper thing. There’s ppl that like to print the code into paper and if IIRC, in plain text, it one can only write 80 characters in each line. The problem arises when nesting creates much indentation. Those times when one can only write 40 characters due to all indentation that has happened (rare but not that uncommon). As screens are now, I believe, unless there’s still the eager to print the code, 120 characters is a really good way to go.

        “(welcome to closure). ”
        Thx again 😀 I was introduced to that “bayba” 5 years ago! And I love how it works in js!

        “It sounds like you’re using a constructor as a function (without the new prefix)? ”
        Naw, I’m used to objects in javascript (really use the “new” keyword). I just think more like the machine itself does than those wierd paradigms that some talk about.
        A good example is the so-called matrix. I don’t have the concept of the matrix in my mind. When they (teachers) tried to teach me the concept of the matrix I’d always screw up something. So I madeup a different view of it that makes much more sense (if you want me to explain just ask it). Same thing for those closures and similar. The way most ppl teach is too confusing.

        “Re: “eval is Evil””
        Just make a link to some place that explains it in a way you agree. No need to explain in the article yourself.

        “Re: “if Statement””
        The Chrome and FF js compiler (or if you prefer to call, interpreter) will generate a warn if you write “if(a = b)” because it may contain a hard-to-notice bug (the C compiler does the same). By using:
        “if((a = b))” You are confirming that you really meant to write like that to whoever reads the code and also the compiler. Minifiers, like google closure compiler, are able to remove the excess parenthesis. This is just a helper to while code is tested and while code is read.

        “Thanks for your comments.”
        Ur welcome.
        It’s also in these situations that ppl learn a lot. We can find our mistakes and fix ourselves and we can also find other’s mistakes so that can fix themselves to create better and greater… Whatever we do.

  4. brunoais Says:

    “JavaScript does not have macros or constants, so there isn’t much point in using all caps to signify features that JavaScript doesn’t have.”
    We better already prepare for ECMAScript 6.0. So it’s ok to use const, let and var and use full CAPS for const.

    ” tags should be placed as late in the body as possible.”
    Just use defer or async (depending on the objective).
    The one that is really reliable is async.
    Actually I made intensive tests on this for an open-source project I’m working on, some months ago on Firefox, Opera, Chrome, IE8, IE9 and IE10. The results show that except for IE8 and IE9, the best way is definitely to place in the , before any tags for CSS, with @async or @defer, depending on the objective. If you really want it to show ok also to IE8 and IE9, just use the conditional HTML tags that MS made for IE and place the tags both in the and the end of the body.

    Also, careful with what you write. The current stable standard is HTML4.1 and “” is not valid HTML4 (only HTML5) (this is just a headsup).

    “Tabs and Indenting”
    I use and always used tabs for indenting. There’s no standard about tab stops, true, but is there a standard for spaces? Is that 4 spaces correct? Why not use tabs and read the file with tabs as 4 spaces? I still wanted to know about that.

    “Avoid lines longer than 80 characters”
    Why? What’s the problem of having a line with 81 characters?
    I have already made code with 120, or so, characters that actually was more readable than placing it in two lines. Actually, to stay readable I would have to have it in 4 lines (believe it or not).

    “By convention, the name of that variable I use is that.”
    I use “me”, I have already read code that uses “_this”. Anyway both seem ok.

    That privileged method… I only remember that js had public methods.
    Those functions declared inside the constructor… Why not making it an anonymous function and storing it in a variable? If you do that they do not belong to the window object but to the variable in which you store it, instead.
    You are introducing here concepts that the language itself does not know what it is. You may create, later, problems related to it.

    “eval is Evil”
    I agree, but better state why, not just saying that it is evil. You may just use a link to a place where it explains why is it evil.

    “Scoping”
    You should mention the “let” too. It is already defined, at least, in the latest ECMAScript spec.

    In “Loose Augmentation”
    Are you talking about the script@async?

    “if Statement”
    In the part:
    “if (a = b) {”
    If one wants to use like that, then he should use:
    ‘if ((a = b)) {‘
    Instead to show that he really meant to use like that. Browsers like firefox warns the developer if he uses
    “if (a = b) {“,
    so better if we don’t.

    How about the if … in …, huh?

    That’s all I have to do. With the rest, I never used such stuff or I agree with you.
    Good luck and have fun.

  5. Kristie Lloyd Says:

    This is really interesting, You’re a very skilled blogger. I’ve
    joined your feed and look forward to seeking more of your wonderful post.
    Also, I have shared your website in my social networks!

  6. Brent Says:

    Way cool! Some very valid points! I appreciate you writing this article.

  7. How to Increase Software Developer Productivity | Binarymist Says:

    […] compiled a set of these here: JavaScript Coding Standards and Guidelines Generic Coding Standards and Guidelines C#.NET Coding Standards and […]

  8. JavaScript Object Creation Patterns | Binarymist Says:

    […] counter measures do we have at our disposal to make sure this doesn’t happen? Naming conventions. Enforcing new is used with JavaScript constructor functions? pg 45 – 46 of Stoyan […]

  9. universityofbridgeport.net Says:

    Many thanks for writing “JavaScript Coding Standards and Guidelines | Binarymist”.
    I reallymight absolutely be back for alot more reading through and writing comments
    soon. Thanks, Ophelia

  10. Extending, Currying and Monkey Patching. part 1 | Binarymist Says:

    […] may have noticed, I’m using the module pattern in the above example. This pattern is effective for getting our objects nicely nested into a single […]

  11. gonzesse Says:

    Article super cultivant

Leave a comment