JavaScript Coding style — Firefox Source Docs documentation (original) (raw)

Coding style

prettier is the tool used to reformat the JavaScript code.

Methods and functions

In JavaScript, functions should use camelCase, but should not capitalize the first letter. Methods should not use the named function expression syntax, because our tools understand method names:

doSomething: function (aFoo, aBar) { ... }

In-line functions should have spaces around braces, except before commas or semicolons:

function valueObject(aValue) { return { value: aValue }; }

JavaScript objects

var foo = { prop1: "value1" };

var bar = { prop1: "value1", prop2: "value2" };

Constructors for objects should be capitalized and use Pascal Case:

function ObjectConstructor() { this.foo = "bar"; }

Operators

In JavaScript, overlong expressions not joined by && and|| should break so the operator starts on the second line and starting in the same column as the beginning of the expression in the first line. This applies to ?:, binary arithmetic operators including +, and member-of operators. Rationale: an operator at the front of the continuation line makes for faster visual scanning, as there is no need to read to the end of line. Also there exists a context-sensitive keyword hazard in JavaScript; see {{bug(442099, “bug”, 19)}}, which can be avoided by putting . at the start of a continuation line, in long member expression.

In JavaScript, == is preferred to ===.

Unary keyword operators, such as typeof, should have their operand parenthesized; e.g. typeof("foo") == "string".

Literals

Double-quoted strings (e.g. "foo") are preferred to single-quoted strings (e.g. 'foo'), in JavaScript, except to avoid escaping embedded double quotes, or when assigning inline event handlers.

Prefixes

Other advice