Appendix A. JavaScript Style Guide

Programming language style guides are important for the long-term maintainability of software. This guide is based on the Code Conventions for the Java Programming Language and Douglas Crockford’s Code Conventions for the JavaScript Programming Language. Modifications have been made due to my personal experience and preferences.

Indentation

Each indentation level is made up of four spaces. Do not use tabs.

// Good
if (true) {
    doSomething();
}

Line Length

Each line should be no longer than 80 characters. If a line goes longer than 80 characters, it should be wrapped after an operator (comma, plus, etc.). The following line should be indented two levels (eight characters).

// Good
doSomething(argument1, argument2, argument3, argument4,
        argument5);

// Bad: Following line only indented four spaces
doSomething(argument1, argument2, argument3, argument4,
    argument5);

// Bad: Breaking before operator
doSomething(argument1, argument2, argument3, argument4
        , argument5);

Primitive Literals

Strings should always use double quotes (never single quotes) and should always appear on a single line. Never use a slash to create a new line in a string.

// Good
var name = "Nicholas";

// Bad: Single quotes
var name = 'Nicholas';

// Bad: Wrapping to second line
var longString = "Here's the story, of a man \
named Brady.";

Numbers should be written as decimal integers, e-notation integers, hexadecimal integers, or floating-point decimals with at least one digit before and one digit ...

Get Maintainable JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.