Awesome
Nerdery JavaScript Standards() {
A sensible style guide for writing JavaScript. This is a living, breathing document that will continue to evolve as new language features are unveiled.
Following these conventions will:
- Improve readability
- Minimize common code smells
- Reduce errors and improve maintainability
This document is not intended to:
- Advocate specific frameworks or libraries
- Give advice on design patterns and project architecture
- Guide the reader in learning JavaScript
ESLint Config for the Nerdery JavaScript Standards
Table of Contents
- Types
- Variables
- Objects
- Arrays
- Destructuring
- Strings
- Functions
- Arrow Functions
- Classes
- Modules
- Iterators and Generators
- Properties
- Comparison
- Comments
- Whitespace
- Commas
- Semicolons
- Naming Conventions
- Accessors
- Events
- DOM Interaction
- Asynchronous Operations
- Deployment
- License
Types
<a name="types--assign-consistent"></a><a name="1.1"></a>
-
1.1 A variable should remain the same type it was originally assigned (a number, string, boolean, array, or object). Avoid reassigning variables to a different type.
// bad let count = 1; count = 'Ben Kenobi'; // good let count = 1; count = 2;
<a name="types--return-consistent"></a><a name="1.2"></a>
-
1.2 Values returned by functions should be of a consistent type. Avoid returning multiple different types.
// bad pressYourLuck(bigMoney) { if (bigMoney) { return 'No whammies!'; } return false; };
<a name="types--coercion-explicit"></a><a name="1.3"></a>
- 1.3 Perform type coercion at the beginning of the statement.
<a name="types--coercion-strings"></a><a name="1.4"></a>
-
1.4 Strings:
// this.reviewScore = 9; // bad const totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf() // bad const totalScore = this.reviewScore.toString(); // isn't guaranteed to return a string // good const totalScore = String(this.reviewScore);
<a name="types--coercion-numbers"></a><a name="1.5"></a>
-
1.5 Numbers: Use
Number
for type casting andparseInt
always with a radix for parsing strings. eslint:radix
,no-implicit-coercion
const inputValue = '4'; // bad const val = new Number(inputValue); // bad const val = +inputValue; // bad const val = inputValue >> 0; // good const val = Number(inputValue); // good const val = parseInt(inputValue, 10);
<a name="types--coercion-booleans"></a><a name="1.6"></a>
-
1.6 Booleans:
const age = 0; // bad const hasAge = new Boolean(age); // bad const hasAge = !!age; // good const hasAge = Boolean(age);
<a name="types--comment-deviations"></a><a name="1.7"></a>
-
1.7 Avoid "trick" operators whose purpose is not immediately readable and obvious. If you must use a convoluted syntax for performance reasons, leave a comment explaining why and what you're doing.
// good /** * parseInt was the reason my code was slow. * Bitshifting the String to coerce it to a * Number made it a lot faster. */ const val = inputValue >> 0;
<a name="types--exceptions"></a><a name="1.8"></a>
-
1.8 When an exception is to be thrown, prefer use of one of the built-in Error types or a class that inherits from Error.
-
Why? This provide more semantic messaging and allow for the possibility of catching certain types of errors.
divide(numerator, denominator) { if (denominator === 0) { // bad throw 'string exceptions are harder to handle'; // good throw new RangeError('cannot divide by 0'); } }
Variables
<a name="variables--prefer-const"></a><a name="2.1"></a>
-
2.1 Use
const
for all of your references; avoid usingvar
. eslint:prefer-const
,no-const-assign
Why? This ensures that you can't reassign your references, which can lead to bugs and difficult to comprehend code.
// bad var a = 1; var b = 2; // good const a = 1; const b = 2;
<a name="variables--disallow-var"></a><a name="2.2"></a>
-
2.2 If you must reassign references, use
let
instead ofvar
. eslint:no-var
Why?
let
is block-scoped rather than function-scoped likevar
.// bad var count = 1; count += 1; // good, use the let. let count = 1; count += 1;
<a name="variables--one-const"></a><a name="2.3"></a>
-
2.3 Use one
const
declaration per variable. eslint:one-var
Why? It's easier to add new variable declarations this way, and you never have to worry about swapping out a
;
for a,
or introducing punctuation-only diffs.// bad const items = getItems(), goSportsTeam = true, dragonball = 'z'; // good const items = getItems(); const goSportsTeam = true; const dragonball = 'z';
<a name="variables--const-let-group"></a><a name="2.4"></a>
-
2.4 Group all your
const
s and then group all yourlet
s.Why? This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
// bad let dragonball, items = getItems(), goSportsTeam = true; // bad const items = getItems(); let dragonball; const goSportsTeam = true; // good const goSportsTeam = true; const items = getItems(); let dragonball;
<a name="variables--define-where-used"></a><a name="2.5"></a>
-
2.5 Assign variables near their first use.
Why?
let
andconst
are block scoped and not function scoped.// bad - unnecessary function call checkName(hasName) { const name = getName(); if (hasName === 'test') { return false; } if (name === 'test') { this.setName(''); return false; } return name; } // good checkName(hasName) { if (hasName === 'test') { return false; } const name = getName(); if (name === 'test') { this.setName(''); return false; } return name; }
<a name="variables--always-declare"></a><a name="2.6"></a>
-
2.6 Always use
const
orlet
to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that. eslint:no-undef
// bad superPower = new SuperPower(); // good const superPower = new SuperPower();
<a name="variables--no-chain-assignment"></a><a name="2.7"></a>
-
2.7 Don't chain variable assignments. eslint:
no-multi-assign
Why? Chaining variable assignments creates implicit global variables.
// bad (function example() { // JavaScript interprets this as // let a = ( b = ( c = 1 ) ); // The let keyword only applies to variable a; variables b and c become // global variables. let a = b = c = 1; }()); console.log(a); // undefined console.log(b); // 1 console.log(c); // 1 // good (function example() { let a = 1; let b = a; let c = a; }()); console.log(a); // undefined console.log(b); // undefined console.log(c); // undefined // the same applies for `const`
Objects
<a name="objects--no-new"></a><a name="3.1"></a>
-
3.1 Use the literal syntax for object creation. eslint:
no-new-object
// bad const item = new Object(); // good const item = {};
<a name="objects--reserved-words"></a><a name="3.2"></a>
-
3.2 If your code will be executed in a browser context, don't use reserved words as keys. Use meaningful synonyms instead.
// bad const superman = { class: 'alien', }; // bad const superman = { klass: 'alien', }; // good const superman = { type: 'alien', };
<a name="objects--computed-properties"></a><a name="3.3"></a>
-
3.3 Use computed property names when creating objects with dynamic property names.
Why? They allow you to define all the properties of an object in one place.
function getKey(k) { return `a key named ${k}`; } // bad const obj = { id: 5, name: 'San Francisco', }; obj[getKey('enabled')] = true; // good const obj = { id: 5, name: 'San Francisco', [getKey('enabled')]: true, };
<a name="objects--shorthand"></a><a name="3.4"></a>
-
3.4 Use object method shorthand. eslint:
object-shorthand
// bad const atom = { value: 1, addValue: function (value) { return atom.value + value; }, }; // good const atom = { value: 1, addValue(value) { return atom.value + value; }, };
<a name="objects--concise"></a><a name="3.5"></a>
-
3.5 Use property value shorthand when object keys and values are redundantly named. eslint:
object-shorthand
// bad makePoint(x, y) { return { x: x, y: y }; } // good makePoint(x, y) { return { x, y }; }
<a name="objects--grouped-shorthand"></a><a name="3.6"></a>
-
3.6 Group your shorthand properties at the beginning of your object declaration.
Why? It's easier to tell which properties are using the shorthand.
makePoint(x, y) { return { x, y, color: 'blue', opacity: 0.5 }; }
<a name="objects--quoted-props"></a><a name="3.7"></a>
-
3.7 Only quote properties that are invalid identifiers. eslint:
quote-props
Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.
// bad const bad = { 'foo': 3, 'bar': 4, 'data-blah': 5, }; // good const good = { foo: 3, bar: 4, 'data-blah': 5, };
<a name="objects--rest-spread"></a><a name="3.8"></a>
-
3.8 Prefer the object spread operator over Object.assign to shallow-copy objects. Use the object rest operator to get a new object with certain properties omitted.
// very bad const original = { a: 1, b: 2 }; const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ delete copy.a; // so does this // bad const original = { a: 1, b: 2 }; const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 } // good const original = { a: 1, b: 2 }; const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 } const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
Arrays
<a name="arrays--literals"></a><a name="4.1"></a>
-
4.1 Use the literal syntax for array creation. eslint:
no-array-constructor
// bad const items = new Array(); // good const items = [];
<a name="arrays--push"></a><a name="4.2"></a>
-
4.2 Use Array#push instead of direct assignment to add items to an array.
const someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
<a name="arrays--spreads"></a><a name="4.3"></a>
-
4.3 Use array spreads
...
or the slice() method to make a shallow copy of arrays.// bad const len = items.length; const itemsCopy = []; let i; for (i = 0; i < len; i++) { itemsCopy[i] = items[i]; } // good const itemsCopy = items.slice(); // good const itemsCopy = [...items];
<a name="arrays--from"></a><a name="4.4"></a>
-
4.4 To convert an array-like object to an array, use Array#from.
const foo = document.querySelectorAll('.foo'); const nodes = Array.from(foo);
<a name="arrays--callback-return"></a><a name="4.5"></a>
-
4.5 Use return statements in array method callbacks. It's ok to omit the return if the function body consists of a single statement. eslint:
array-callback-return
// bad [1, 2, 3].map(x => { const y = x + 1; }); // good [1, 2, 3].map(x => { const y = x + 1; return x * y; }); // good [1, 2, 3].map(x => x + 1);
<a name="arrays--bracket-newline"></a><a name="4.6"></a>
-
4.6 Use line breaks after open and before close array brackets if an array has multiple lines
// bad const objectInArray = [{ id: 1, }, { id: 2, }]; // good const objectInArray = [ { id: 1, }, { id: 2, }, ];
Destructuring
<a name="destructuring--object"></a><a name="5.1"></a>
-
5.1 Use object destructuring when accessing and using multiple properties of an object.
Why? Destructuring saves you from creating temporary references for those properties.
// bad getFullName(user) { const firstName = user.firstName; const lastName = user.lastName; return `${firstName} ${lastName}`; } // good getFullName(user) { const { firstName, lastName } = user; return `${firstName} ${lastName}`; } // good getFullName({ firstName, lastName }) { return `${firstName} ${lastName}`; }
<a name="destructuring--array"></a><a name="5.2"></a>
-
5.2 Use array destructuring.
const arr = [1, 2, 3, 4]; // bad const first = arr[0]; const second = arr[1]; // good const [first, second] = arr;
<a name="destructuring--object-over-array"></a><a name="5.3"></a>
-
5.3 Use object destructuring for multiple return values, not array destructuring.
Why? You can add new properties over time or change the order of things without breaking call sites.
// bad processInput(input) { // then a miracle occurs return [left, right, top, bottom]; } // the caller needs to think about the order of return data const [left, __, top] = processInput(input); // good processInput(input) { // then a miracle occurs return { left, right, top, bottom }; } // the caller selects only the data they need const { left, right } = processInput(input);
Strings
<a name="strings--quotes"></a><a name="6.1"></a>
-
6.1 Use single quotes
''
for strings. eslint:quotes
// bad const name = "Capt. Janeway"; // good const name = 'Capt. Janeway';
<a name="strings--line-length"></a><a name="6.2"></a>
-
6.2 Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation.
Why? Broken strings are painful to work with and make code less searchable.
// bad const errorMessage = 'This is a super long error that was thrown because \ of Batman. When you stop to think about how Batman had anything to do \ with this, you would get nowhere \ fast.'; // bad const errorMessage = 'This is a super long error that was thrown because ' + 'of Batman. When you stop to think about how Batman had anything to do ' + 'with this, you would get nowhere fast.'; // good const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
<a name="strings--template-literals"></a><a name="6.4"></a>
-
6.4 When programmatically building up strings, use template strings instead of concatenation. eslint:
prefer-template
template-curly-spacing
Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.
// bad sayHi(name) { return 'How are you, ' + name + '?'; } // bad sayHi(name) { return ['How are you, ', name, '?'].join(); } // bad sayHi(name) { return `How are you, ${ name }?`; } // good sayHi(name) { return `How are you, ${name}?`; }
<a name="strings--eval"></a><a name="6.5"></a>
<a name="strings--sanitize"></a><a name="6.6"></a>
- 6.6 Never inject untrusted strings into the DOM unless the value has been sanitized. Untrusted strings include anything a user or external source can manipulate, such as query parameters, cookie values, or results from an AJAX call.
Functions
<a name="functions--mutate-parameters"></a><a name="7.1"></a>
-
7.1 Never mutate parameters. eslint:
no-param-reassign
Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.
// bad foo(obj) { obj.key = 1; } // good foo(obj) { const key = obj.key != null ? obj.key : 1; }
<a name="functions--reassign-parameters"></a><a name="7.2"></a>
-
7.2 Never reassign parameters. eslint:
no-param-reassign
Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the
arguments
object. It can also cause optimization issues, especially in V8.// bad foo(name) { name = name || 'Tony Stark'; } // good foo(name) { const localName = name || 'Tony Stark'; } // good foo(name = 'Tony Stark') { const localName = name; }
<a name="functions--default-parameters"></a><a name="7.3"></a>
-
7.3 When arguments may be omitted completely, use default parameter syntax.
// bad // This won't work as expected, the default parameter will // only be assigned if the value provided is `undefined` signup(name = 'Tony Stark') { // ... } signup(null); // good signup(name = 'Tony Stark') { // ... } signup();
<a name="functions--default-side-effects"></a><a name="7.4"></a>
-
7.4 Avoid side effects with default parameters.
Why? They are confusing to reason about.
// bad count(a = b++) { // ... }
<a name="functions--defaults-last"></a><a name="7.5"></a>
-
7.5 Always put default parameters last.
handleThings(opts = {}, name) { // ... } // good handleThings(name, opts = {}) { // ... }
<a name="functions--too-many-parameters"></a><a name="7.6"></a>
-
7.6 Do not create functions with more than 5 parameters. When you must have that many parameters, pass in an object instead.
max-params
// bad signup(birthdate, address, city, state, zip, name) { // ... } // good signup({ birthdate, address, city, state, zip, name }) { // ... } // good // Pass an instance of a `UserInfo` object signup(userInfo) { // .. }
<a name="functions--arguments-shadow"></a><a name="7.7"></a>
-
7.7 Never name a parameter
arguments
. This will take precedence over thearguments
object that is given to every function scope.// bad nope(name, options, arguments) { // ... } // good yup(name, options, args) { // ... }
<a name="functions--arguments-shadow"></a><a name="7.8"></a>
-
7.8 Never use
arguments
, opt to use rest syntax...
instead.prefer-rest-params
Why?
...
is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like likearguments
.// bad concatenateAll() { const args = Array.prototype.slice.call(arguments); return args.join(''); } // good concatenateAll(...args) { return args.join(''); }
<a name="functions--in-blocks"></a><a name="7.9"></a>
-
7.9 Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears. eslint:
no-inner-declarations
// bad if (currentUser) { function test() { console.log('Nope.'); } } // good let test; if (currentUser) { test = () => { console.log('Yup.'); }; }
<a name="functions--constructor"></a><a name="7.10"></a>
-
7.10 Never use the Function constructor to create a new function. eslint:
no-new-func
Why? Creating a function in this way evaluates a string similarly to eval(), which opens vulnerabilities.
// bad const add = new Function('a', 'b', 'return a + b');
<a name="functions--exit-early"></a><a name="7.11"></a>
-
7.11 Prefer a single return at the end of the function. Avoid adding multiple returns in the middle of a function, since they make the flow harder to debug and encourage inconsistent return types.
// bad login(userId) { if (userId != null) { return getUser(userId); } else { return new User(); } }; // good login(userId) { let user = null; if (userId != null) { user = getUser(userId); } else { user = new User(); } return user; };
<a name="functions--exit-early"></a><a name="7.12"></a>
-
7.12 An exception to the above for guard clauses: if asserting whether parameters are valid, exit early using return statements at the beginning of the function.
add(num1, num2) { if (isNaN(num1) || isNaN(num2)) { return false; } // ... };
<a name="functions--iife"></a><a name="7.13"></a>
-
7.13 Add parantheses around immediately invoked function expressions. eslint:
wrap-iife
Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this. Note that in a world with modules everywhere, you almost never need an IIFE.
// immediately-invoked function expression (IIFE) (function () { console.log('Welcome to the Internet. Please follow me.'); }());
Arrow Functions
<a name="arrows--use-them"></a><a name="8.1"></a>
-
8.1 When you must use function expressions (as when passing an anonymous function), use arrow function notation. eslint:
prefer-arrow-callback
,arrow-spacing
Why? It creates a version of the function that executes in the context of
this
, which is usually what you want, and is a more concise syntax.Why not? If you have a fairly complicated function, you might move that logic out into its own function declaration.
// bad [1, 2, 3].map(function (x) { const y = x + 1; return x * y; }); // good [1, 2, 3].map(x => { const y = x + 1; return x * y; });
<a name="arrows--one-arg-parens"></a><a name="8.2"></a>
-
8.2 If your function takes a single argument, omit the parentheses. Otherwise, always include parentheses around arguments. eslint:
arrow-parens
Why? Less visual clutter.
// bad [1, 2, 3].map((x) => x * x); // good [1, 2, 3].map(x => x * x);
Classes
<a name="classes--use-them"></a><a name="9.1"></a>
-
9.1 Always use
class
. Avoid manipulatingprototype
directly.Why?
class
syntax is more concise and easier to reason about.// bad function Queue(contents = []) { this.queue = [...contents]; } Queue.prototype.queue = []; Queue.prototype.pop = function () { const value = this.queue[0]; this.queue.splice(0, 1); return value; }; // good class Queue { queue = []; constructor(contents = []) { this.queue = [...contents]; } pop() { const value = this.queue[0]; this.queue.splice(0, 1); return value; } }
<a name="classes--static"></a><a name="9.2"></a>
-
9.2 Use
static
for declaring class-wide properties and methods.// bad class Queue { constructor() { Queue.instanceCount++; } } Queue.instanceCount = 0; Queue.getInstanceCount = function() { return this.instanceCount; } // good class Queue { static instanceCount = 0; constructor() { Queue.instanceCount++; } static getInstanceCount() { return this.instanceCount; } }
<a name="classes--extends"></a><a name="9.3"></a>
-
9.3 Use
extends
for inheritance.Why? It is a built-in way to inherit prototype functionality without breaking
instanceof
.// bad function PeekableQueue(contents) { Queue.apply(this, contents); } PeekableQueue.prototype = new Queue(); PeekableQueue.prototype.constructor = PeekableQueue; PeekableQueue.prototype.peek = function () { return this.queue[0]; } // good class PeekableQueue extends Queue { peek() { return this.queue[0]; } }
<a name="classes--tostring"></a><a name="9.4"></a>
-
9.4 It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.
class Jedi { constructor(options = {}) { this.name = options.name || 'no name'; } getName() { return this.name; } toString() { return `Jedi - ${this.getName()}`; } }
<a name="classes--no-duplicate-members"></a><a name="9.5"></a>
-
9.5 Avoid duplicate class members. eslint: [
no-dupe-class-members
] (http://eslint.org/docs/rules/no-dupe-class-members)Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug.
// bad class Foo { bar() { return 1; } bar() { return 2; } }
Modules
<a name="modules--separate"></a><a name="10.1"></a>
- 10.1 Create a separate module for each logical set of functionality in your application. Avoid grouping multiple areas of concern or the whole application into a single file.
<a name="modules--use-them"></a><a name="10.2"></a>
-
10.2 Always use modules (
import
/export
) over a non-standard module system. You can always transpile to your preferred module system.Why? Modules are the future, let's start using the future now.
// bad const NerderyStyleGuide = require('./NerderyStyleGuide'); // good import NerderyStyleGuide from './NerderyStyleGuide';
<a name="modules--prefer-default-export"></a><a name="10.3"></a>
-
10.3 In modules with a single export, prefer default export over named export. eslint:
import/prefer-default-export
// bad export function foo() {} // good export default function foo() {}
<a name="modules--no-wildcard"></a><a name="10.4"></a>
-
10.4 Do not use wildcard imports.
Why? This makes sure you have a single default export.
// bad import * as NerderyStyleGuide from './NerderyStyleGuide'; // good import NerderyStyleGuide from './NerderyStyleGuide';
<a name="modules--self-host"></a><a name="10.5"></a>
-
10.5 Self-host third-party libraries whenever possible. Avoid loading third-party scripts from external domains and CDN's. Exceptions are libraries that do not provide self-hosted versions, such as Google Maps or Analytics.
Why? Doing so exposes users to additional attack vectors, privacy violations (IP address tracking) and additional downtime risks.
// bad import $ from 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js'; // good import $ from './vendor/jquery.min.js';
Iterators and Generators
<a name="iterators--nope"></a><a name="11.1"></a>
-
11.1 Avoid using iterators and
for-of
loops. Prefer JavaScript's higher-order functions instead of loops likefor-in
orfor-of
.Use
map()
/every()
/filter()
/find()
/findIndex()
/reduce()
/some()
/ ... to iterate over arrays, andObject.keys()
/Object.values()
/Object.entries()
to produce arrays so you can iterate over objects.const numbers = [1, 2, 3, 4, 5]; // bad let sum = 0; for (let num of numbers) { sum += num; } // good let sum = 0; numbers.forEach(num => sum += num); // best (use the functional force) const sum = numbers.reduce((total, num) => total + num, 0); // bad const increasedByOne = []; for (let i = 0; i < numbers.length; i++) { increasedByOne.push(numbers[i] + 1); } // good const increasedByOne = []; numbers.forEach(num => increasedByOne.push(num + 1)); // best (keeping it functional) const increasedByOne = numbers.map(num => num + 1);
<a name="generators--nope"></a><a name="11.2"></a>
-
11.2 Don't use generators for now.
Why? They don't transpile well to ES5.
Properties
<a name="properties--dot"></a><a name="12.1"></a>
-
12.1 Use dot notation when accessing properties. eslint:
dot-notation
const luke = { jedi: true, age: 28, }; // bad const isJedi = luke['jedi']; // good const isJedi = luke.jedi;
<a name="properties--bracket"></a><a name="12.2"></a>
-
12.2 Use bracket notation
[]
when accessing properties with a variable.const luke = { jedi: true, age: 28, }; const prop = 'jedi'; const isJedi = luke[prop];
Comparison
<a name="comparison--eqeqeq"></a><a name="13.1"></a>
-
13.1 Use
===
and!==
over==
and!=
. eslint:eqeqeq
// bad if (dragonball == 'z') { //... } // good if (dragonball === 'z') { //... }
<a name="comparison--eqeq-null"></a><a name="13.2"></a>
-
13.2 The one allowable exception is null checks. Use
==
and!=
to compare against null.Why? The
==
checks for both null and undefined in a single expression.// bad if (dragonball === null || dragonball === undefined) { //... } // good if (dragonball == null) { //... }
<a name="comparison--no-shortcuts"></a><a name="13.3"></a>
-
13.3 Use shortcuts for booleans, but explicit comparisons for strings and numbers.
Why? JavaScript will try to coerce strings and numbers into a boolean value, which could lead to unintended results. Be more descriptive about what you want to compare. For more information see Truth Equality and JavaScript by Angus Croll.
// bad if (isValid === true) { // ... } // good if (isValid) { // ... } // bad if (name) { // ... } // good if (name !== '') { // ... } // bad if (collection.length) { // ... } // good if (collection.length > 0) { // ... }
<a name="comparison--switch-blocks"></a><a name="13.4"></a>
-
13.4 Use braces to create blocks in
case
anddefault
clauses that contain lexical declarations (e.g.let
,const
,function
, andclass
). eslint:no-case-declarations
.Why? Lexical declarations are visible in the entire
switch
block but only get initialized when assigned, which only happens when itscase
is reached. This causes problems when multiplecase
clauses attempt to define the same thing.// bad switch (number) { case 1: const x = 1; break; case 2: const y = 2; break; default: const z = 3; } // good switch (number) { case 1: { const x = 1; break; } case 2: { const y = 2; break; } default: { const z = 3; } }
<a name="comparison--nested-ternaries"></a><a name="13.5"></a>
-
13.5 Ternaries should not be nested and should be single line expressions. eslint:
no-nested-ternary
.// bad const foo = maybe1 > maybe2 ? 'bar' : value1 > value2 ? 'baz' : null; // good const maybeNull = value1 > value2 ? 'baz' : null; const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
Blocks
<a name="blocks--braces"></a><a name="14.1"></a>
-
14.1 Use braces with all multi-line blocks. eslint:
curly
// bad if (test) return false; // good if (test) { return false; }
<a name="blocks--cuddled-elses"></a><a name="14.2"></a>
-
14.2 If you're using multi-line blocks with
if
andelse
, putelse
on the same line as yourif
block's closing brace. eslint:brace-style
// bad if (test) { thing1(); } else { thing2(); } // good if (test) { thing1(); } else { thing2(); }
Comments
<a name="comments--multiline"></a><a name="15.1"></a>
-
15.1 Use
/** ... */
for multi-line comments. Include types for all parameters and return values. eslint:valid-jsdoc
// bad // make() returns a new element // based on the passed in tag name // // @method make // @public // @param {String} tag // @return {Element} element make(tag) { // ... return element; } // good /** * make() returns a new element * based on the passed in tag name * * @method make * @public * @param {String} tag * @return {Element} element */ make(tag) { // ... return element; }
<a name="comments--singleline"></a><a name="15.2"></a>
-
15.2 Use
//
for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it's on the first line of a block.// bad const active = true; // is current tab // good // is current tab const active = true; // bad getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this._type || 'no type'; return type; } // good getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this._type || 'no type'; return type; } // also good getType() { // set the default type to 'no type' const type = this._type || 'no type'; return type; }
<a name="comments--actionitems"></a><a name="15.3"></a>
-
15.3 Prefix any comments that are meant to be revisited later with
FIXME
orTODO
.Why? helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable.
<a name="comments--fixme"></a><a name="15.4"></a>
-
15.4 Use
// FIXME:
to annotate problems.class Calculator extends Abacus { constructor() { super(); // FIXME: shouldn't use a global here total = 0; } }
<a name="comments--todo"></a><a name="15.5"></a>
-
15.5 Use
// TODO:
to annotate refactoring recommendations.class Calculator extends Abacus { constructor() { super(); // TODO: total should be configurable by an options param this.total = 0; } }
Whitespace
<a name="whitespace--spaces"></a><a name="16.1"></a>
-
16.1 Use soft tabs set to 4 spaces. eslint:
indent
// bad test() { ∙∙console.log('test'); } // good test() { ∙∙∙∙console.log('test'); }
<a name="whitespace--before-blocks"></a><a name="16.2"></a>
-
16.2 Place 1 space before the leading brace. eslint:
space-before-blocks
// bad test(){ console.log('test'); } // good test() { console.log('test'); } // bad dog.set('attr',{ age: '1 year', breed: 'Bernese Mountain Dog', }); // good dog.set('attr', { age: '1 year', breed: 'Bernese Mountain Dog', });
<a name="whitespace--around-keywords"></a><a name="16.3"></a>
-
16.3 Place 1 space before the opening parenthesis in control statements (
if
,while
etc.). Place no space between the argument list and the function name in function calls and declarations. eslint:keyword-spacing
,space-before-function-paren
// bad if(isJedi) { fight (); } // good if (isJedi) { fight(); } // bad fight () { console.log ('Swooosh!'); } // good fight() { console.log('Swooosh!'); }
<a name="whitespace--infix-ops"></a><a name="16.4"></a>
-
16.4 Set off operators with spaces. eslint:
space-infix-ops
// bad const x=y+5; // good const x = y + 5;
<a name="whitespace--newline-at-end"></a><a name="16.5"></a>
-
16.5 End files with a single newline character. eslint:
eol-last
// bad export default class TacoTuesday { // .. }
// bad export default class TacoTuesday { // .. }↵ ↵
// good export default class TacoTuesday { // .. }↵
<a name="whitespace--chains"></a><a name="16.6"></a>
-
16.6 Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which emphasizes that the line is a method call, not a new statement. eslint:
newline-per-chained-call
// bad $('#items').find('.selected').highlight().end().find('.open').updateCount(); // bad $('#items'). find('.selected'). highlight(). end(). find('.open'). updateCount(); // good $('#items') .find('.selected') .highlight() .end() .find('.open') .updateCount(); // good const leds = stage.selectAll('.led').data(data);
<a name="whitespace--after-blocks"></a><a name="16.7"></a>
-
16.7 Leave a blank line after blocks and before the next statement.
// bad if (foo) { return bar; } return baz; // good if (foo) { return bar; } return baz; // bad const obj = { foo() { }, bar() { }, }; return obj; // good const obj = { foo() { }, bar() { }, }; return obj;
<a name="whitespace--padded-blocks"></a><a name="16.8"></a>
-
16.8 Do not pad your blocks with blank lines. eslint:
padded-blocks
// bad bar() { console.log(foo); } // also bad if (baz) { console.log(qux); } else { console.log(foo); } // good bar() { console.log(foo); } // good if (baz) { console.log(qux); } else { console.log(foo); }
<a name="whitespace--in-parens"></a><a name="16.9"></a>
-
16.9 Do not add spaces inside parentheses. eslint:
space-in-parens
// bad bar( foo ) { return foo; } // good bar(foo) { return foo; } // bad if ( foo ) { console.log(foo); } // good if (foo) { console.log(foo); }
<a name="whitespace--in-brackets"></a><a name="16.10"></a>
-
16.10 Do not add spaces inside brackets. eslint:
array-bracket-spacing
// bad const foo = [ 1, 2, 3 ]; console.log(foo[ 0 ]); // good const foo = [1, 2, 3]; console.log(foo[0]);
<a name="whitespace--in-braces"></a><a name="16.11"></a>
-
16.11 Add spaces inside curly braces. eslint:
object-curly-spacing
// bad const foo = {clark: 'kent'}; // good const foo = { clark: 'kent' };
<a name="whitespace--signature-invocation-indentation"></a><a name="16.12"></a>
-
16.12 Functions with multiline signatures, or invocations, should be indented with each item on a line by itself, with a trailing comma on the last item.
// bad function foo(bar, baz, quux) { // ... } // good function foo( bar, baz, quux, ) { // ... } // bad console.log(foo, bar, baz); // good console.log( foo, bar, baz, );
<a name="whitespace--max-len"></a><a name="16.13"></a>
-
16.13 Avoid having lines of code that are longer than 100 characters (including whitespace). eslint:
max-len
Why? This ensures readability and maintainability.
// bad $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.')); // good const foo = 'Whatever national crop flips the window. The cartoon reverts within the screw. ' + 'Whatever wizard constrains a helpful ally. The counterpart ascends!'; // good $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' }, }) .done(() => console.log('Congratulations!')) .fail(() => console.log('You have failed this city.'));
Commas
<a name="commas--multiline"></a><a name="17.1"></a>
-
17.1 Use trailing commas for multi-line arrays and objects. eslint:
comma-style
comma-dangle
Why? This leads to cleaner git diffs.
// bad const heroes = [ 'Batman' , 'Superman' ]; // bad const heroes = [ 'Batman', 'Superman' ]; // good const heroes = [ 'Batman', 'Superman', ]; // bad const hero = { firstName: 'Ada' , lastName: 'Lovelace' }; // bad const hero = { firstName: 'Ada', lastName: 'Lovelace' }; // good const hero = { firstName: 'Ada', lastName: 'Lovelace', };
<a name="commas--singleline"></a><a name="17.2"></a>
-
17.2 No trailing commas for single-line arrays and objects. eslint:
comma-dangle
// bad const heroes = ['Batman', 'Superman',]; // good const heroes = ['Batman', 'Superman']; // bad const hero = { firstName: 'Ada', lastName: 'Lovelace', }; // good const hero = { firstName: 'Ada', lastName: 'Lovelace' };
Semicolons
<a name="semicolons--required"></a><a name="18.1"></a>
-
// bad const name = 'Skywalker' return name // good const name = 'Skywalker'; return name;
Naming Conventions
<a name="naming--verbs-nouns"></a><a name="19.1"></a>
-
19.1 Method names should be verbs, properties should be nouns.
// bad class Plane { flew = 0; powering = 4; airborne() { // ... } grounded() { // ... } } // good class Plane { altitude = 0; engineCount = 4; takeoff() { // ... } land() { // ... } }
<a name="naming--boolean-prefix"></a><a name="19.2"></a>
-
19.2 If the property/method is a
boolean
, prefix withis
,has
,are
,should
.// bad if (visible) // ... } // good if (isVisible) // ... } // bad if (hero.superPower()) // ... } // good if (hero.hasSuperPower()) // ... }
<a name="naming--descriptive"></a><a name="19.3"></a>
-
19.3 Be descriptive with your naming. Avoid single letter names unless it corresponds with the problem domain, such as
i
for indexes orx/y/z
for coordinates.// bad q() { // ... } // good query() { // ... } // bad return { a: 0, b: 0, c: 0 }; // good return { x: 0, y: 0, z: 0 };
<a name="naming--camelCase"></a><a name="19.4"></a>
-
19.4 Use camelCase when naming objects, functions, and instances. eslint:
camelcase
// bad const OBJEcttsssss = {}; const this_is_my_object = {}; function c() {} // good const thisIsMyObject = {}; function thisIsMyFunction() {}
<a name="naming--PascalCase"></a><a name="19.5"></a>
-
19.5 Use PascalCase when naming constructors or classes. eslint:
new-cap
// bad function user(options) { this.name = options.name; } const bad = new user({ name: 'nope', }); // good class User { constructor(options) { this.name = options.name; } } const good = new User({ name: 'yup', });
<a name="naming--leading-underscore"></a><a name="19.6"></a>
-
19.6 Use a leading underscore
_
when naming private or protected properties.// bad this.__firstName__ = 'Panda'; this.firstName_ = 'Panda'; // good this._firstName = 'Panda';
<a name="naming--self-this"></a><a name="19.7"></a>
-
19.7 Don't save references to
this
. Use arrow functions or Function#bind.// bad foo() { const self = this; return function () { console.log(self); }; } // bad foo() { const that = this; return function () { console.log(that); }; } // good foo() { return () => { console.log(this); }; }
<a name="naming--filename-matches-export"></a><a name="19.8"></a>
-
19.8 If your file exports a single class, your filename should be exactly the name of the class.
// file contents class CheckBox { // ... } export default CheckBox; // in some other file // bad import CheckBox from './checkBox'; // bad import CheckBox from './check_box'; // good import CheckBox from './CheckBox';
<a name="naming--constants"></a><a name="19.9"></a>
-
19.9 Constant values should be in all capitals and underscore-separated.
const MAXIMUM_POWER = 9000;
<a name="naming--constants-grouping"></a><a name="19.10"></a>
-
19.10 Group related constants in an object. All properties should be named using the same convention for constants.
// bad const SELECTOR_ACTIVE = '.isActive'; const SELECTOR_DISABLED = '.isDisabled'; const SELECTOR_MODAL_CLOSE = '.js-modal-close'; // good const SELECTORS = { ACTIVE: '.isActive', DISABLED: '.isDisabled', MODAL_CLOSE: '.js-modal-close', };
<a name="naming--symbols"></a><a name="19.11"></a>
-
19.11 If the values you set for constants are arbitrary and don't add meaning, use Symbol() instead.
// bad const NAVIGATION = { HOME: 'home', ABOUT: 'about', CONTACT: 'contact', } // good const NAVIGATION = { HOME: Symbol(), ABOUT: Symbol(), CONTACT: Symbol(), }
Accessors
<a name="accessors--use-them"></a><a name="20.1"></a>
-
20.1 When getting and setting properties, use
get
andset
accessor methods.//bad class Dragon { _age = 0; getAge() { return this._age; } setAge(value) { this._age = value; } } const dragon = new Dragon(); dragon.setAge(25); console.log(dragon.getAge()); // 25
prefer:
//good class Dragon { _age = 0; get age() { return this._age; } set age(value) { this._age = value; } } const dragon = new Dragon(); dragon.age = 25; console.log(dragon.age); // 25
<a name="accessors--no-side-effects"></a><a name="20.2"></a>
-
20.2 Getter methods should not exhibit side effects.
//bad get age() { if (this.isBirthday()) { this._age++; } return this._age; } //good get age() { return this._age; }
Events
<a name="events--hash"></a><a name="21.1"></a>
-
21.1 When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:
// bad $(this).trigger('listingUpdated', listing.id); ... $(this).on('listingUpdated', (e, listingId) => { // do something with listingId });
prefer:
// good $(this).trigger('listingUpdated', { listingId: listing.id }); ... $(this).on('listingUpdated', (e, data) => { // do something with data.listingId });
DOM Interaction
<a name="dom--dollar-prefix"></a><a name="22.1"></a>
-
22.1 Prefix jQuery object variables with a
$
.// bad const body = $(document.body); // good const $body = $(document.body);
<a name="dom--selector-prefix"></a><a name="22.2"></a>
-
22.2 DOM elements to be selected by JavaScript should be prefixed with js-. These selectors should not be related to any CSS styles and must exist solely for the accessing of those DOM elements.
// bad <a href="#" class="previousButton">Previous</a> const $previousButton = $('.previousButton'); // good <a href="#" class="previousButton js-previousButton">Previous</a> const $previousButton = $('.js-previousButton');
<a name="dom--selector-match"></a><a name="22.3"></a>
-
22.3 If the behavior of a DOM element is tied to a JavaScript class, the selector should be named the same as that JavaScript class.
// bad <div class="js-carousel"></div> new CarouselView($('.js-carousel')); // good <div class="js-CarouselView"></div> new CarouselView($('.js-CarouselView'));
<a name="jquery--cache"></a><a name="22.4"></a>
-
22.4 Cache jQuery lookups.
// bad $('.sidebar').hide(); $('.sidebar').css({ 'background-color': 'pink' }); // good const $sidebar = $('.sidebar'); $sidebar.hide(); $sidebar.css({ 'background-color': 'pink' });
Asynchronous Operations
<a name="asynchronous--promise-spec"></a><a name="23.1"></a>
-
23.1 When performing an asynchronous operation, wrap that operation with a Promise. Use a Promise implementation that conforms with the Promises/A+ spec.
waitFor(milliseconds) { return new Promise((resolve, reject) => { window.setTimeout( () => { resolve(); }, milliseconds ); }); } waitFor(1000) .then(() => { console.log('Done waiting!'); });
<a name="asynchronous--nested-promises"></a><a name="23.2"></a>
-
23.2 Avoid nesting promises several layers deep. Instead, compose a sequence of promises using a flat chain. Better yet, use the await syntax.
// bad waitFor(1000) .then(() => { waitFor(2000) .then(() => { waitFor(3000) .then(() => { console.log('Done waiting!'); }) }) }); // good waitFor(1000) .then(() => { return waitFor(2000); }) .then(() => { return waitFor(3000); }) .then(() => { console.log('Done waiting!'); }); // best async function mySequence() { await waitFor(1000); await waitFor(2000); await waitFor(3000); console.log('Done waiting!'); }
<a name="asynchronous--catch"></a><a name="23.3"></a>
-
23.3 Always add a catch() handler to promise chains.
Why? In some browsers, if code inside of a promise executes and generates a runtime error, it will silently fail and never be reported to the console.
waitFor(1000) .then(() => { console.log('Done waiting!'); }) .catch(exception => { console.error('Error in waitFor():', exception); });
Deployment
<a name="deployment--minify"></a><a name="24.1"></a>
- 24.1 All JavaScript deployed to a production environment must be minified and combined. Test your minified/combined code early, as it may behave differently or exhibit unforeseen JavaScript errors.
License
(The MIT License)
Copyright (c) 2014-2017 Airbnb
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.