JavaScript Style Guide

JavaScript is a very forgiving programming language. As a result, the same bit of code written by two different JavaScript programmers will often look quite different. Conforming to a set of stylistic guidelines ensures that all code looks as though it were written by a single programmer even when multiple programmers are involved. It also makes code easier to read and understand.

In this guide, we'll provide a set of JavaScript coding guidelines that you can adopt to write cleaner, elegant code, and ensure a consistent programming style is used.

A Guiding Principle

When programming in any language, including JavaScript, emphasize clarity over cleverness.

This means that the goal of the programmer should be to write code in a way that is as readable as possible rather than to use the fewest number of keystrokes. If there are two ways to do a thing — and in JavaScript there are often a half-dozen or more ways to do a thing — use the method that offers the most clarity rather than the method that is the most clever.

For example:

// Clever, but potentially confusing
;[ 'foo', 'bar', 'baz', 'qux' ].forEach ( function () {
  // Function code
} );

// Somewhat verbose, but clear
var foobars = [ 'foo', 'bar', 'baz', 'qux' ];
function somethingClever () {
  // Function code
};
foobars.forEach( somethingClever );

Comments

Since we'll be using comments throughout this guide, let's address comment styling first.

Programmers should err on the side of providing too many comments rather than too few. Comments are an invaluable way to help other developers understand what's going on and also help the original developer remember the purpose of each bit of code.

There are three types of comments that can be used in JavaScript:

  • Single line comments.
  • Multi line comments.
  • Inline comments.

Here is how we recommend formatting each type of comment:

/**
  This is a multi-line comment. This type of comment
  should be reserved for file headings and to describe
  the purpose of complex functions.
  */

// This is a single line comment. Use it to provide short notes.

// Try to avoid inline comments as seen below.
var foobars = [ 'foo', 'qux' /* also quux and quuux */ ];

Single and multi-line comments should always be preceded by a blank line. In addition, single line comments should appear above the code they describe, not next to or below it.

Multi line comments can be formatted in many different ways.

/***********************************************************
 *                                                         *
 *  Some developers like to create large blocks            *
 *  in which to nest multi line comments. It certainly     *
 *  isn't our preference, but the key here is consistency. *
 *  If you're going to use this format, just make sure to  *
 *  use it consistently.                                   *
 *                                                         *
 ***********************************************************/

/**
  * Our preference is for simplicity. Multi-line comments
  * typed out simply require less effort and are just as
  * easy to read - and present less of an eyesore if you
  * ask us. We recommend the use of a single forward slash
  * and two asterisks to open a multi-line comment. Then,
  * each line begins with two space indentation, an
  * asterisk, and a space. The comment is closed with a
  * two space indentation, an asterisk, and the closing
  * forward slash.
  */

/***********************************************************

  But this style of comments is arguably as readable as
  the other styles. And it has the advantage of being
  easy to maintain, regardless of the editor that the
  programmer is using.

 ***********************************************************/

Whitespace, Line Breaks, Columns, and Indentation

The proper use of space is the single most important determiner of code readability. Code that is consistently spaced and indented is far easier to read than the alternative.

Indentation

Let's start with indentation. While indentation practices vary, the predominant indentation method — and the method we recommend — is to indent with the use of two spaces. Indentation can be configured in virtually every integrated development environment (IDE) or text editor, so just set indentation to 2 spaces and you should be good to go.

Columns

When we talk about columns in programming, what we're referring to is the number of characters that should appear in a row before adding a line break. For the sake of readability, it is important to add line breaks. In general, the consensus is that 80 characters, or columns, is a good break-point. Others perfect smaller lengths, like 65.

One additional issue that will require illustration is the use of indentation following a line break. When that occurs, the best thing to do is to indent the wrapped content 4 spaces rather than 2 as shown in the example below:

var foo = 'This variable contains a very long ' +
    'string that will break out over multiple ' +
    'lines. For the sake of clarity, the ' +
    'content appearing on new lines should be ' +
    'indented four spaces.',
  bar = 'Indenting in this way makes it easier' +
    ' to visually differentiate between line ' +
    'breaks due to column wrap and line breaks' +
    ' at the end of a statement.';
(Note that we are using shorter line lengths to make them look good on this webpage.)

Whitespace

A few additional best-practice rules for the use of whitespace include:

  • Avoid end-of-line and blank line whitespace. That is, avoid leaving an empty space at the end of a line of code or on an empty line. Turning on "show invisibles" or "draw white space" in most text editors and IDEs will display these characters so that you can spot and eliminate them.
  • Add a space after commas in lists, like this: var foo = [ 'bar', 'baz', 'qux' ];.
  • Add whitespace between parentheses and their contents, like this: function( foo )....
  • Add whitespace between operators and content when concatenating a string, like this: 'Hello ' + 'world!'.
  • Adding a single blank line to separate and group of related bits of code is fine. Adding multiple lines is not recommended.

Naming

When naming functions, variables, and other items in JavaScript here are a few rules to observe:

  • Use human readable names that are intuitively meaningful whenever possible.
  • Use plural names for arrays and singular names for other types of variables.
  • Use camelCase to name functions and variables, like this: var longName = '';.
  • Use PascalCase when naming constructors (object classes), like this: function HostingCompany( name, url, rating) {....
  • If you create symbolic constants, name them by using all caps and underscores, like this: var MAX_RATING = 100;.
  • When creating regular expressions, prefix the name with a lower case r, like this for validating email addresses: var rEmail = /[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,63};.

Semicolons

Virtually all modern JavaScript implementations include a feature called automatic semicolon insertion (ASI). This feature intuits where semicolons are supposed to appear and adds them automatically. As a result, some programmers encourage others to never use semicolons with the exception of a few edge cases. Others programmers encourage you to add them as if ASI did not exist.

We're solidly in the latter camp. We've just seen too many concatenated JavaScript files break to think it's okay to omit them.

The question then becomes, when should semicolons be added? In general, semicolons should be added after every declaration or assignment. For example:

var foo = '';
foo = 1;
foo++;
foo = function() {
  // Semicolon needed because this function is being assigned to a variable.
};
alert( foo );
console.log( foo );

Semicolons are not needed after the closing curly brace of a statement or function — unless the function is assigned as the value of a variable as demonstrated in the last bit of code. However, if you do add semicolons after functions and statements you aren't going to break anything in doing so.

In addition, semicolons should never be added between the closing paranthesis and opening curly brace in a statement or function like this: function( parameter ); {... or if ( condition ); {....

Quotes

In JavaScript, either single quotes or double quotes may be used. However, the consensus among most published style guides is in favor of the use of single quotes — a consensus we are happy to go along with. When you need to use more than one set of quotes, such as when nesting HTML inside of JavaScript, alternate between single and double quotes.

// Do this
var foo = 'bar';

// Not this
var foo = "bar";

// This is ok
var foo = '<div class=\'trouble\'>Some content here.</div>';

// But this is easier and more readable
var foo = '<div class="trouble">Some content here.</div>';

Variables

JavaScript is very forgiving in allowing variables to be declared in a wide variety of formats. We recommend using a format that is as readable and clear as possible.

// This is bad because it is hard to read. Don't do this.
var foo = "", bar = [], baz = {}, qux = function () { 
    /* Insert statements here. */ };

//This is bad because it is inconsistent.
var foo = '', 
  bar = [];
var baz = {};
qux = function () { /* Insert statements here. */ };

// This is good because it is consistent and legible.
var foo = '',
  bar = [],
  baz = {},
  qux = function () {
    // Insert statements here.
  };

// This is best.
var foo = '';
var bar = [];
var baz = {};
var qux = function () {
    // Insert statements here.
  };

There are many times when you will want to declare a variable inside of a function or inside of an if...else statement. When that happens, group all of your variables together and declare them first.

Arrays and Objects

Creating complex arrays and objects has the potential to produce highly illegible code. For this reason, proper indentation and the use of line breaks is critical. Let's review a few examples of good and poor coding practice with regard to the creation of arrays and objects.

// It's okay to declare short, simple arrays on a single line.
var foobars = [ 'foo', 'bar', 'baz', 'qux' ];

// Long arrays should be declared with line breaks.
var emailAddresses = [
  '<a href="mailto:[email protected]">Contact Us</a>',
  '<a href="mailto:[email protected]">Webmaster</a>',
  '<a href="mailto:[email protected]">Sales</a>',
  '<a href="mailto:[email protected]">Support</a>'
];

// Objects should always be declared with line breaks.
var placeholders = {
  1: 'foo',
  2: 'bar',
  3: 'baz',
  4: 'qux'
};

Statements and Functions

Properly formatting statements and functions makes them easier to understand and can also help avoid issues when code is concatenated or rendered by a browser. Here is how functions and statements should generally be formatted:

function functionName() {
  // Insert code here.
}

That basic format should be followed for functions, if statements, for statements, while statements, and so forth. The rules that dictate that style include:

  • Always place the opening bracket on the same line as the function or statement parameters like this: ( parameters ) {.... Adding a line break between the closing parenthesis and opening bracket can cause automatic semicolon insertion (ASI) to break code by adding semicolons improperly.
  • Always break statements and functions onto multiple lines with all function or statement code appearing on the lines between the opening and closing brackets.

Nesting Functions

Nesting functions inside of functions as shown in the next example is perfectly acceptable:

function fooBar( foo ) {
  var bar = function() {
    // Function code here.
  }
  function nestedFunction() {
    // More function code here.
  }
  return nestedFunction( bar );
}

However, nesting functions inside of statements should only be done when the function is assigned to a variable. This is because the ECMAScript standard does not support nested functions in statements. While most JavaScript implementations will handle this improper use just fine, implementations that follow ECMAScript more strictly will not process the code correctly.

The following example illustrates the difference:

if ( foo > bar ) {

  // Don't do this
  function fooBar( foo, bar ) {
    foobar = foo + bar;
    return foobar;
  }
  fooBar( foo, bar );

  // Do this instead
  var foobar = function fooBar( foo, bar ) {
    return foo + bar;
  }
}

When writing if...else statements, make it clear that the entire statement is connected by avoiding the addition of line breaks before each portion of the statement.


// Use the following format.
if ( condition ) {
  // Insert statements here.
} else if ( condition ) {
  // Additional statements here.
} else {
  // Even more statements here.
}

// Don't do this. It's confusing.
if ( condition ) {
  // Insert statements here.
} 
else if ( condition ) {
  // Additional statements here.
} 
else {
  // Even more statements here.
}

Comparison

When comparing two values in JavaScript you have two options. You can check for either strict equality by using === and !== or you can check for abstract equality by using == and !=.

The difference between the two options is that when you check for abstract equality the JavaScript machine will attempt to convert the value types before returning false. However, when you check for strict equality, the machine will only return true if both the type and value are a match. Here are a few examples of how this can play out in practice:

// A number
var foo = 0;

// A string
var bar = '0';

// Evaluates to 'true'
foo == bar;
foo == false;
bar == false;
foo !== bar;

// Evaluates to 'false'
foo != bar;
foo === bar;
foo === false;
foo === false;

The use of abstract comparisons can lead to confusion about variable types. As a result, we recommend sticking to strict comparisons to avoid the following sort of issue:

// A string
var foo = '123';

// A number
var bar = 123;

// Will return true
foo == bar;

// Will return false
foo === bar;

If you use abstract comparison you may think both values are equal to the number "123" when foo is actually equal to the string "123." As a result, you may try to perform mathematical calculations with the string in foo. Strict comparison of the values will clue you in to the issue and let you know that you need to convert foo into a number before performing a calculation.

Resources

In creating this style guide we consulted the following resources:

Summary

Using a consistent and thoughtful style when writing JavaScript can make your code easier to read and understand. In addition, using a consistent style when working on projects that involve multiple developers ensures that all code is present in a consistent manner.

In this guide, we've presented a suggested style for writing JavaScript code. Adopt it, modify it to suit your needs, and reap the benefits of cleaner, clearer, more consistent code.


Further Reading and Resources

We have more guides, tutorials, and infographics related to coding and development:

What Code Should You Learn?

Confused about what programming language you should learn to code in? Check out our infographic, What Code Should You Learn? It not only discusses different aspects of the languages, it answers important questions such as, "How much money will I make programming JavaScript for a living?"