Home Indentation and Spacing in JavaScript

Indentation

Spacing and indentation should be consistent throughout your code. Many developers choose to use 4-space or 2-space indentation. In JavaScript, each nested statement (e.g., a statement following a "{" brace) should be indented exactly once more than the previous line's indentation.

Here are some examples of bad indentation in JavaScript:

function foo() {
var x = 2;
console.log(x);
}

  function bar() {
console.log(1);
  }

Here are some examples of good indentation in JavaScript:

function foo() {
  var x = 2;
  console.log(x);
}

function bar() {
  console.log(1);
}

Line Formatting

Line Breaks

Opening "{" brackets should be on the same line as the function/loop/conditional header, and corresponding closing "}" brackets should be on their own line and indented to align with the indentation of the line that has the corresponding opening "{".

Here are some examples of bad line breaks in JavaScript:

function foo() { var x = 2; console.log(x);}

function bar()
{
  var y = 1;
  console.log(y);
}

Here are some examples of good line breaks in JavaScript:

function foo() {
  var x = 2;
  console.log(x);
}

function bar() {
  var y = 1;
  console.log(y);
}

Long Lines

Lines should never be longer than 100 characters in JavaScript, and many developers aim at 80 characters as the line character limit. When any line is longer than 100 characters, break it into two lines by pressing Enter after an operator and reindenting the line. Indent the trailing second part of the line such that it aligns with the first letter of the first word following the opening "=" above if one exists (for variable assignments), otherwise aligned with the character following the opening "(" on the previous line.

Here are some examples of bad reindentation of long lines:

var result = reallyLongFunctionOne() + reallyLongFunctionTwo() +
reallyLongFunctionThree() + reallyLongFunctionFour();

var result2 = reallyLongFunction(parameterOne, parameterTwo, 
parameterThree, parameterFour);

Here are some examples of good reindentation of long lines:

var result = reallyLongFunctionOne() + reallyLongFunctionTwo() +
             reallyLongFunctionThree() + reallyLongFunctionFour();

var result2 = reallyLongFunction(parameterOne, parameterTwo, 
                                 parameterThree, parameterFour);

Blank Lines

Place a blank line between the end of each JavaScript function and the start of the next function's function comment. You should not have more than one blank line in a row.

function foo() {
  var x = 2;
  console.log(x);
}
function bar() {
  console.log("hi");
}
// Prints 2 to the console
function foo() {
  var x = 2;
  console.log(x);
}

// Prints "hi" to the console
function bar() {
  console.log("hi");
}

Spacing

Spacing in Expressions

Place a space between operators, assigments ("=") and their operands.

var x=(a+b)*c/d+foo();
var x = (a + b) * c / d + foo();