JavaScript Coding Convention: WhiteSpace

  • Indentation with tabs.
  • No trailing whitespace.
  • Use blank lines to separate one block of logically related code from another.
  • One space on both sides of binary operators and assignment operators.
  • Keywords followed by a “(" (left parenthesis) must be separated by one space. This gives visual distinction between keywords and function invocations.
  • There should be no space between the function name and left parenthesis of an argument list.
  • There should be one space on the insides of parentheses (such as in if statements, function calls, and arguments lists).
  • Don’t use operators as if they are functions (such as delete, void, typeof, new, return, ..).

Whitespace examples

INCORRECT

a.foo=bar+baz;

if( foo ){
foo.bar = doBar () ;
}

function foo () {
return bar;
};

foo = function() {
return('bar');
};

foo = typeof( bar );

function baz(foo, bar) {
return 'gaz';
}

baz('banana', 'pear');

foo = bar[0];
foo = bar[baz];
foo = [bar,baz];

CORRECT

a.foo = bar + baz;

if ( foo ) {
foo.bar = doBar();
}

function foo() {
return bar;
}

foo = function () {
return 'bar';
};

foo = typeof bar;

function baz( foo, bar ) {
return 'gaz';
}

baz( 'banana', 'pear' );

foo = bar[ 0 ];
foo = bar[ baz ];
foo = [ bar, baz ];

Trusted Veteran | Compassionate. Aspiring. Resourceful.