Airbnb JavaScript Style Guide() {
A mostly reasonable approach to JavaScript
> Note: this guide assumes you are using Babel, and requires that you use babel-preset-airbnb or the equivalent. It also assumes you are installing shims/polyfills in your app, with airbnb-browser-shims or the equivalent.
This guide is available in other languages too. See Translation
Other Style Guides
Table of Contents
Comparison Operators & Equality
ECMAScript 6+ (ES 2015+) Styles
The JavaScript Style Guide Guide
Types
1.1 Primitives: When you access a primitive type you work directly on its value.
string
number
boolean
null
undefined
symbol
bigint
javascript
1const foo = 1; 2 let bar = foo; 3 4 bar = 9; 5 6 console.log(foo, bar); // => 1, 9
Symbols and BigInts cannot be faithfully polyfilled, so they should not be used when targeting browsers/environments that don’t support them natively.
1.2 Complex: When you access a complex type you work on a reference to its value.
object
array
function
javascript
1const foo = [1, 2]; 2 const bar = foo; 3 4 bar[0] = 9; 5 6 console.log(foo[0], bar[0]); // => 9, 9
References
2.1 Use const for all of your references; avoid using var. 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.
javascript
1// bad 2 var a = 1; 3 var b = 2; 4 5 // good 6 const a = 1; 7 const b = 2;
2.2 If you must reassign references, use let instead of var. eslint: no-var
> Why? let is block-scoped rather than function-scoped like var.
javascript
1// bad 2 var count = 1; 3 if (true) { 4 count += 1; 5 } 6 7 // good, use the let. 8 let count = 1; 9 if (true) { 10 count += 1; 11 }
2.3 Note that both let and const are block-scoped, whereas var is function-scoped.
javascript
1// const and let only exist in the blocks they are defined in. 2 { 3 let a = 1; 4 const b = 1; 5 var c = 1; 6 } 7 console.log(a); // ReferenceError 8 console.log(b); // ReferenceError 9 console.log(c); // Prints 1
In the above code, you can see that referencing a and b will produce a ReferenceError, while c contains the number. This is because a and b are block scoped, while c is scoped to the containing function.
Objects
3.1 Use the literal syntax for object creation. eslint: no-new-object
javascript
1// bad 2 const item = new Object(); 3 4 // good 5 const item = {};
3.2 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.
javascript
1function getKey(k) { 2 return `a key named ${k}`; 3 } 4 5 // bad 6 const obj = { 7 id: 5, 8 name: 'San Francisco', 9 }; 10 obj[getKey('enabled')] = true; 11 12 // good 13 const obj = { 14 id: 5, 15 name: 'San Francisco', 16 [getKey('enabled')]: true, 17 };
3.3 Use object method shorthand. eslint: object-shorthand
javascript
1// bad 2 const atom = { 3 value: 1, 4 5 addValue: function (value) { 6 return atom.value + value; 7 }, 8 }; 9 10 // good 11 const atom = { 12 value: 1, 13 14 addValue(value) { 15 return atom.value + value; 16 }, 17 };
3.4 Use property value shorthand. eslint: object-shorthand
> Why? It is shorter and descriptive.
javascript
1const lukeSkywalker = 'Luke Skywalker'; 2 3 // bad 4 const obj = { 5 lukeSkywalker: lukeSkywalker, 6 }; 7 8 // good 9 const obj = { 10 lukeSkywalker, 11 };
3.5 Group your shorthand properties at the beginning of your object declaration.
> Why? It’s easier to tell which properties are using the shorthand.
javascript
1const anakinSkywalker = 'Anakin Skywalker'; 2 const lukeSkywalker = 'Luke Skywalker'; 3 4 // bad 5 const obj = { 6 episodeOne: 1, 7 twoJediWalkIntoACantina: 2, 8 lukeSkywalker, 9 episodeThree: 3, 10 mayTheFourth: 4, 11 anakinSkywalker, 12 }; 13 14 // good 15 const obj = { 16 lukeSkywalker, 17 anakinSkywalker, 18 episodeOne: 1, 19 twoJediWalkIntoACantina: 2, 20 episodeThree: 3, 21 mayTheFourth: 4, 22 };
3.6 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.
javascript
1// bad 2 const bad = { 3 'foo': 3, 4 'bar': 4, 5 'data-blah': 5, 6 }; 7 8 // good 9 const good = { 10 foo: 3, 11 bar: 4, 12 'data-blah': 5, 13 };
3.7 Do not call Object.prototype methods directly, such as hasOwnProperty, propertyIsEnumerable, and isPrototypeOf. eslint: no-prototype-builtins
> Why? These methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false } - or, the object may be a null object (Object.create(null)). In modern browsers that support ES2022, or with a polyfill such as , Object.hasOwn can also be used as an alternative to Object.prototype.hasOwnProperty.call.
javascript
1// bad 2 console.log(object.hasOwnProperty(key)); 3 4 // good 5 console.log(Object.prototype.hasOwnProperty.call(object, key)); 6 7 // better 8 const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope. 9 console.log(has.call(object, key)); 10 11 // best 12 console.log(Object.hasOwn(object, key)); // only supported in browsers that support ES2022 13 14 /* or */ 15 import has from 'has'; // https://www.npmjs.com/package/has 16 console.log(has(object, key)); 17 /* or */ 18 console.log(Object.hasOwn(object, key)); // https://www.npmjs.com/package/object.hasown
3.8 Prefer the object spread syntax over Object.assign to shallow-copy objects. Use the object rest parameter syntax to get a new object with certain properties omitted. eslint: prefer-object-spread
javascript
1// very bad 2 const original = { a: 1, b: 2 }; 3 const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ 4 delete copy.a; // so does this 5 6 // bad 7 const original = { a: 1, b: 2 }; 8 const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 } 9 10 // good 11 const original = { a: 1, b: 2 }; 12 const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 } 13 14 const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
Arrays
4.1 Use the literal syntax for array creation. eslint: no-array-constructor
javascript
1// bad 2 const items = new Array(); 3 4 // good 5 const items = [];
4.2 Use Array#push instead of direct assignment to add items to an array.
javascript
1const someStack = []; 2 3 // bad 4 someStack[someStack.length] = 'abracadabra'; 5 6 // good 7 someStack.push('abracadabra');
4.3 Use array spreads ... to copy arrays.
javascript
1// bad 2 const len = items.length; 3 const itemsCopy = []; 4 let i; 5 6 for (i = 0; i < len; i += 1) { 7 itemsCopy[i] = items[i]; 8 } 9 10 // good 11 const itemsCopy = [...items];
4.4 To convert an iterable object to an array, use spreads ... instead of Array.from
javascript
1const foo = document.querySelectorAll('.foo'); 2 3 // good 4 const nodes = Array.from(foo); 5 6 // best 7 const nodes = [...foo];
4.5 Use Array.from for converting an array-like object to an array.
javascript
1const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 }; 2 3 // bad 4 const arr = Array.prototype.slice.call(arrLike); 5 6 // good 7 const arr = Array.from(arrLike);
4.6 Use Array.from instead of spread ... for mapping over iterables, because it avoids creating an intermediate array.
javascript
1// bad 2 const baz = [...foo].map(bar); 3 4 // good 5 const baz = Array.from(foo, bar);
4.7 Use return statements in array method callbacks. It’s ok to omit the return if the function body consists of a single statement returning an expression without side effects, following 8.2. eslint: array-callback-return
javascript
1// good 2 [1, 2, 3].map((x) => { 3 const y = x + 1; 4 return x * y; 5 }); 6 7 // good 8 [1, 2, 3].map((x) => x + 1); 9 10 // bad - no returned value means `acc` becomes undefined after the first iteration 11 [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { 12 const flatten = acc.concat(item); 13 }); 14 15 // good 16 [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { 17 const flatten = acc.concat(item); 18 return flatten; 19 }); 20 21 // bad 22 inbox.filter((msg) => { 23 const { subject, author } = msg; 24 if (subject === 'Mockingbird') { 25 return author === 'Harper Lee'; 26 } else { 27 return false; 28 } 29 }); 30 31 // good 32 inbox.filter((msg) => { 33 const { subject, author } = msg; 34 if (subject === 'Mockingbird') { 35 return author === 'Harper Lee'; 36 } 37 38 return false; 39 });
4.8 Use line breaks after opening array brackets and before closing array brackets, if an array has multiple lines
javascript
1// bad 2 const arr = [\ 3 [0, 1], [2, 3], [4, 5],\ 4 ]; 5 6 const objectInArray = [{\ 7 id: 1,\ 8 }, {\ 9 id: 2,\ 10 }]; 11 12 const numberInArray = [\ 13 1, 2,\ 14 ]; 15 16 // good 17 const arr = [[0, 1], [2, 3], [4, 5]]; 18 19 const objectInArray = [\ 20 {\ 21 id: 1,\ 22 },\ 23 {\ 24 id: 2,\ 25 },\ 26 ]; 27 28 const numberInArray = [\ 29 1,\ 30 2,\ 31 ];
Destructuring
5.1 Use object destructuring when accessing and using multiple properties of an object. eslint: prefer-destructuring
> Why? Destructuring saves you from creating temporary references for those properties, and from repetitive access of the object. Repeating object access creates more repetitive code, requires more reading, and creates more opportunities for mistakes. Destructuring objects also provides a single site of definition of the object structure that is used in the block, rather than requiring reading the entire block to determine what is used.
javascript
1// bad 2 function getFullName(user) { 3 const firstName = user.firstName; 4 const lastName = user.lastName; 5 6 return `${firstName} ${lastName}`; 7 } 8 9 // good 10 function getFullName(user) { 11 const { firstName, lastName } = user; 12 return `${firstName} ${lastName}`; 13 } 14 15 // best 16 function getFullName({ firstName, lastName }) { 17 return `${firstName} ${lastName}`; 18 }
5.2 Use array destructuring. eslint: prefer-destructuring
javascript
1const arr = [1, 2, 3, 4]; 2 3 // bad 4 const first = arr[0]; 5 const second = arr[1]; 6 7 // good 8 const [first, second] = arr;
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.
javascript
1// bad 2 function processInput(input) { 3 // then a miracle occurs 4 return [left, right, top, bottom]; 5 } 6 7 // the caller needs to think about the order of return data 8 const [left, __, top] = processInput(input); 9 10 // good 11 function processInput(input) { 12 // then a miracle occurs 13 return { left, right, top, bottom }; 14 } 15 16 // the caller selects only the data they need 17 const { left, top } = processInput(input);
Strings
6.1 Use single quotes '' for strings. eslint: quotes
javascript
1// bad 2 const name = "Capt. Janeway"; 3 4 // bad - template literals should contain interpolation or newlines 5 const name = `Capt. Janeway`; 6 7 // good 8 const name = 'Capt. Janeway';
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.
javascript
1// bad 2 const errorMessage = 'This is a super long error that was thrown because \ 3 of Batman. When you stop to think about how Batman had anything to do \ 4 with this, you would get nowhere \ 5 fast.'; 6 7 // bad 8 const errorMessage = 'This is a super long error that was thrown because ' + 9 'of Batman. When you stop to think about how Batman had anything to do ' + 10 'with this, you would get nowhere fast.'; 11 12 // good 13 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.';
6.3 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.
javascript
1// bad 2 function sayHi(name) { 3 return 'How are you, ' + name + '?'; 4 } 5 6 // bad 7 function sayHi(name) { 8 return ['How are you, ', name, '?'].join(); 9 } 10 11 // bad 12 function sayHi(name) { 13 return `How are you, ${ name }?`; 14 } 15 16 // good 17 function sayHi(name) { 18 return `How are you, ${name}?`; 19 }
6.4 Never use eval() on a string; it opens too many vulnerabilities. eslint: no-eval
6.5 Do not unnecessarily escape characters in strings. eslint: no-useless-escape
> Why? Backslashes harm readability, thus they should only be present when necessary.
javascript
1// bad 2 const foo = '\'this\' \i\s \"quoted\"'; 3 4 // good 5 const foo = '\'this\' is "quoted"'; 6 const foo = `my name is '${name}'`;
Functions
7.1 Use named function expressions instead of function declarations. eslint: func-style, func-names
> Why? Function declarations are hoisted, which means that it’s easy - too easy - to reference the function before it is defined in the file. This harms readability and maintainability. If you find that a function’s definition is large or complex enough that it is interfering with understanding the rest of the file, then perhaps it’s time to extract it to its own module! Don’t forget to explicitly name the expression, regardless of whether or not the name is inferred from the containing variable (which is often the case in modern browsers or when using compilers such as Babel). This eliminates any assumptions made about the Error’s call stack. ( Discussion)
javascript
1// bad 2 function foo() { 3 // ... 4 } 5 6 // bad 7 const foo = function () { 8 // ... 9 }; 10 11 // good 12 // lexical name distinguished from the variable-referenced invocation(s) 13 const short = function longUniqueMoreDescriptiveLexicalFoo() { 14 // ... 15 };
7.2 Wrap immediately invoked function expressions in parentheses. 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.
javascript
1// immediately-invoked function expression (IIFE) 2 (function () { 3 console.log('Welcome to the Internet. Please follow me.'); 4 }());
7.3 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-loop-func
7.4 Note: ECMA-262 defines a block as a list of statements. A function declaration is not a statement.
javascript
1// bad 2 if (currentUser) { 3 function test() { 4 console.log('Nope.'); 5 } 6 } 7 8 // good 9 let test; 10 if (currentUser) { 11 test = () => { 12 console.log('Yup.'); 13 }; 14 }
7.5 Never name a parameter arguments. This will take precedence over the arguments object that is given to every function scope.
javascript
1// bad 2 function foo(name, options, arguments) { 3 // ... 4 } 5 6 // good 7 function foo(name, options, args) { 8 // ... 9 }
7.6 Never use arguments, opt to use rest syntax ... instead. eslint: prefer-rest-params
> Why? ... is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like like arguments.
javascript
1// bad 2 function concatenateAll() { 3 const args = Array.prototype.slice.call(arguments); 4 return args.join(''); 5 } 6 7 // good 8 function concatenateAll(...args) { 9 return args.join(''); 10 }
7.7 Use default parameter syntax rather than mutating function arguments.
javascript
1// really bad 2 function handleThings(opts) { 3 // No! We shouldn’t mutate function arguments. 4 // Double bad: if opts is falsy it'll be set to an object which may 5 // be what you want but it can introduce subtle bugs. 6 opts = opts || {}; 7 // ... 8 } 9 10 // still bad 11 function handleThings(opts) { 12 if (opts === void 0) { 13 opts = {}; 14 } 15 // ... 16 } 17 18 // good 19 function handleThings(opts = {}) { 20 // ... 21 }
7.8 Avoid side effects with default parameters.
> Why? They are confusing to reason about.
javascript
1let b = 1; 2 // bad 3 function count(a = b++) { 4 console.log(a); 5 } 6 count(); // 1 7 count(); // 2 8 count(3); // 3 9 count(); // 3
7.9 Always put default parameters last. eslint: default-param-last
javascript
1// bad 2 function handleThings(opts = {}, name) { 3 // ... 4 } 5 6 // good 7 function handleThings(name, opts = {}) { 8 // ... 9 }
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.
javascript
1// bad 2 const add = new Function('a', 'b', 'return a + b'); 3 4 // still bad 5 const subtract = Function('a', 'b', 'return a - b');
7.11 Spacing in a function signature. eslint: space-before-function-paren space-before-blocks
> Why? Consistency is good, and you shouldn’t have to add or remove a space when adding or removing a name.
javascript
1// bad 2 const f = function(){}; 3 const g = function (){}; 4 const h = function() {}; 5 6 // good 7 const x = function () {}; 8 const y = function a() {};
7.12 Never mutate parameters. eslint: no-param-reassign
> Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.
javascript
1// bad 2 function f1(obj) { 3 obj.key = 1; 4 } 5 6 // good 7 function f2(obj) { 8 const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1; 9 }
7.13 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.
javascript
1// bad 2 function f1(a) { 3 a = 1; 4 // ... 5 } 6 7 function f2(a) { 8 if (!a) { a = 1; } 9 // ... 10 } 11 12 // good 13 function f3(a) { 14 const b = a || 1; 15 // ... 16 } 17 18 function f4(a = 1) { 19 // ... 20 }
7.14 Prefer the use of the spread syntax ... to call variadic functions. eslint: prefer-spread
> Why? It’s cleaner, you don’t need to supply a context, and you can not easily compose new with apply.
javascript
1// bad 2 const x = [1, 2, 3, 4, 5]; 3 console.log.apply(console, x); 4 5 // good 6 const x = [1, 2, 3, 4, 5]; 7 console.log(...x); 8 9 // bad 10 new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5])); 11 12 // good 13 new Date(...[2016, 8, 5]);
7.15 Functions with multiline signatures, or invocations, should be indented just like every other multiline list in this guide: with each item on a line by itself, with a trailing comma on the last item. eslint: function-paren-newline
javascript
1// bad 2 function foo(bar, 3 baz, 4 quux) { 5 // ... 6 } 7 8 // good 9 function foo( 10 bar, 11 baz, 12 quux, 13 ) { 14 // ... 15 } 16 17 // bad 18 console.log(foo, 19 bar, 20 baz); 21 22 // good 23 console.log( 24 foo, 25 bar, 26 baz, 27 );
Arrow Functions
8.1 When you must use an anonymous function (as when passing an inline callback), 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 named function expression.
javascript
1// bad 2 [1, 2, 3].map(function (x) { 3 const y = x + 1; 4 return x * y; 5 }); 6 7 // good 8 [1, 2, 3].map((x) => { 9 const y = x + 1; 10 return x * y; 11 });
8.2 If the function body consists of a single statement returning an expression without side effects, omit the braces and use the implicit return. Otherwise, keep the braces and use a return statement. eslint: arrow-parens, arrow-body-style
> Why? Syntactic sugar. It reads well when multiple functions are chained together.
javascript
1// bad 2 [1, 2, 3].map((number) => { 3 const nextNumber = number + 1; 4 `A string containing the ${nextNumber}.`; 5 }); 6 7 // good 8 [1, 2, 3].map((number) => `A string containing the ${number + 1}.`); 9 10 // good 11 [1, 2, 3].map((number) => { 12 const nextNumber = number + 1; 13 return `A string containing the ${nextNumber}.`; 14 }); 15 16 // good 17 [1, 2, 3].map((number, index) => ({ 18 [index]: number, 19 })); 20 21 // No implicit return with side effects 22 function foo(callback) { 23 const val = callback(); 24 if (val === true) { 25 // Do something if callback returns true 26 } 27 } 28 29 let bool = false; 30 31 // bad 32 foo(() => bool = true); 33 34 // good 35 foo(() => { 36 bool = true; 37 });
8.3 In case the expression spans over multiple lines, wrap it in parentheses for better readability.
> Why? It shows clearly where the function starts and ends.
javascript
1// bad 2 ['get', 'post', 'put'].map((httpMethod) => Object.prototype.hasOwnProperty.call( 3 httpMagicObjectWithAVeryLongName, 4 httpMethod, 5 ) 6 ); 7 8 // good 9 ['get', 'post', 'put'].map((httpMethod) => ( 10 Object.prototype.hasOwnProperty.call( 11 httpMagicObjectWithAVeryLongName, 12 httpMethod, 13 ) 14 ));
8.4 Always include parentheses around arguments for clarity and consistency. eslint: arrow-parens
> Why? Minimizes diff churn when adding or removing arguments.
javascript
1// bad 2 [1, 2, 3].map(x => x * x); 3 4 // good 5 [1, 2, 3].map((x) => x * x); 6 7 // bad 8 [1, 2, 3].map(number => ( 9 `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!` 10 )); 11 12 // good 13 [1, 2, 3].map((number) => ( 14 `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!` 15 )); 16 17 // bad 18 [1, 2, 3].map(x => { 19 const y = x + 1; 20 return x * y; 21 }); 22 23 // good 24 [1, 2, 3].map((x) => { 25 const y = x + 1; 26 return x * y; 27 });
8.5 Avoid confusing arrow function syntax (=>) with comparison operators (<=, >=). eslint: no-confusing-arrow
javascript
1// bad 2 const itemHeight = (item) => item.height <= 256 ? item.largeSize : item.smallSize; 3 4 // bad 5 const itemHeight = (item) => item.height >= 256 ? item.largeSize : item.smallSize; 6 7 // good 8 const itemHeight = (item) => (item.height <= 256 ? item.largeSize : item.smallSize); 9 10 // good 11 const itemHeight = (item) => { 12 const { height, largeSize, smallSize } = item; 13 return height <= 256 ? largeSize : smallSize; 14 };
8.6 Enforce the location of arrow function bodies with implicit returns. eslint: implicit-arrow-linebreak
javascript
1// bad 2 (foo) => 3 bar; 4 5 (foo) => 6 (bar); 7 8 // good 9 (foo) => bar; 10 (foo) => (bar); 11 (foo) => ( 12 bar 13 )
Classes & Constructors
9.1 Always use class. Avoid manipulating prototype directly.
> Why? class syntax is more concise and easier to reason about.
javascript
1// bad 2 function Queue(contents = []) { 3 this.queue = [...contents]; 4 } 5 Queue.prototype.pop = function () { 6 const value = this.queue[0]; 7 this.queue.splice(0, 1); 8 return value; 9 }; 10 11 // good 12 class Queue { 13 constructor(contents = []) { 14 this.queue = [...contents]; 15 } 16 pop() { 17 const value = this.queue[0]; 18 this.queue.splice(0, 1); 19 return value; 20 } 21 }
9.2 Use extends for inheritance.
> Why? It is a built-in way to inherit prototype functionality without breaking instanceof.
javascript
1// bad 2 const inherits = require('inherits'); 3 function PeekableQueue(contents) { 4 Queue.apply(this, contents); 5 } 6 inherits(PeekableQueue, Queue); 7 PeekableQueue.prototype.peek = function () { 8 return this.queue[0]; 9 }; 10 11 // good 12 class PeekableQueue extends Queue { 13 peek() { 14 return this.queue[0]; 15 } 16 }
9.3 Methods can return this to help with method chaining.
javascript
1// bad 2 Jedi.prototype.jump = function () { 3 this.jumping = true; 4 return true; 5 }; 6 7 Jedi.prototype.setHeight = function (height) { 8 this.height = height; 9 }; 10 11 const luke = new Jedi(); 12 luke.jump(); // => true 13 luke.setHeight(20); // => undefined 14 15 // good 16 class Jedi { 17 jump() { 18 this.jumping = true; 19 return this; 20 } 21 22 setHeight(height) { 23 this.height = height; 24 return this; 25 } 26 } 27 28 const luke = new Jedi(); 29 30 luke.jump() 31 .setHeight(20);
9.4 It’s okay to write a custom toString() method, just make sure it works successfully and causes no side effects.
javascript
1class Jedi { 2 constructor(options = {}) { 3 this.name = options.name || 'no name'; 4 } 5 6 getName() { 7 return this.name; 8 } 9 10 toString() { 11 return `Jedi - ${this.getName()}`; 12 } 13 }
9.5 Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary. eslint: no-useless-constructor
javascript
1// bad 2 class Jedi { 3 constructor() {} 4 5 getName() { 6 return this.name; 7 } 8 } 9 10 // bad 11 class Rey extends Jedi { 12 constructor(...args) { 13 super(...args); 14 } 15 } 16 17 // good 18 class Rey extends Jedi { 19 constructor(...args) { 20 super(...args); 21 this.name = 'Rey'; 22 } 23 }
9.6 Avoid duplicate class members. eslint: no-dupe-class-members
> Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug.
javascript
1// bad 2 class Foo { 3 bar() { return 1; } 4 bar() { return 2; } 5 } 6 7 // good 8 class Foo { 9 bar() { return 1; } 10 } 11 12 // good 13 class Foo { 14 bar() { return 2; } 15 }
9.7 Class methods should use this or be made into a static method unless an external library or framework requires using specific non-static methods. Being an instance method should indicate that it behaves differently based on properties of the receiver. eslint: class-methods-use-this
javascript
1// bad 2 class Foo { 3 bar() { 4 console.log('bar'); 5 } 6 } 7 8 // good - this is used 9 class Foo { 10 bar() { 11 console.log(this.bar); 12 } 13 } 14 15 // good - constructor is exempt 16 class Foo { 17 constructor() { 18 // ... 19 } 20 } 21 22 // good - static methods aren't expected to use this 23 class Foo { 24 static bar() { 25 console.log('bar'); 26 } 27 }
Modules
10.1 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.
javascript
1// bad 2 const AirbnbStyleGuide = require('./AirbnbStyleGuide'); 3 module.exports = AirbnbStyleGuide.es6; 4 5 // ok 6 import AirbnbStyleGuide from './AirbnbStyleGuide'; 7 export default AirbnbStyleGuide.es6; 8 9 // best 10 import { es6 } from './AirbnbStyleGuide'; 11 export default es6;
10.2 Do not use wildcard imports.
> Why? This makes sure you have a single default export.
javascript
1// bad 2 import * as AirbnbStyleGuide from './AirbnbStyleGuide'; 3 4 // good 5 import AirbnbStyleGuide from './AirbnbStyleGuide';
10.3 And do not export directly from an import.
> Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.
javascript
1// bad 2 // filename es6.js 3 export { es6 as default } from './AirbnbStyleGuide'; 4 5 // good 6 // filename es6.js 7 import { es6 } from './AirbnbStyleGuide'; 8 export default es6;
10.4 Only import from a path in one place.
eslint: no-duplicate-imports
> Why? Having multiple lines that import from the same path can make code harder to maintain.
javascript
1// bad 2 import foo from 'foo'; 3 // … some other imports … // 4 import { named1, named2 } from 'foo'; 5 6 // good 7 import foo, { named1, named2 } from 'foo'; 8 9 // good 10 import foo, { 11 named1, 12 named2, 13 } from 'foo';
10.5 Do not export mutable bindings.
eslint: import/no-mutable-exports
> Why? Mutation should be avoided in general, but in particular when exporting mutable bindings. While this technique may be needed for some special cases, in general, only constant references should be exported.
javascript
1// bad 2 let foo = 3; 3 export { foo }; 4 5 // good 6 const foo = 3; 7 export { foo };
10.6 In modules with a single export, prefer default export over named export.
eslint: import/prefer-default-export
> Why? To encourage more files that only ever export one thing, which is better for readability and maintainability.
javascript
1// bad 2 export function foo() {} 3 4 // good 5 export default function foo() {}
10.7 Put all imports above non-import statements.
eslint: import/first
> Why? Since imports are hoisted, keeping them all at the top prevents surprising behavior.
javascript
1// bad 2 import foo from 'foo'; 3 foo.init(); 4 5 import bar from 'bar'; 6 7 // good 8 import foo from 'foo'; 9 import bar from 'bar'; 10 11 foo.init();
10.8 Multiline imports should be indented just like multiline array and object literals.
eslint: object-curly-newline
> Why? The curly braces follow the same indentation rules as every other curly brace block in the style guide, as do the trailing commas.
javascript
1// bad 2 import {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path'; 3 4 // good 5 import { 6 longNameA, 7 longNameB, 8 longNameC, 9 longNameD, 10 longNameE, 11 } from 'path';
10.9 Disallow Webpack loader syntax in module import statements.
eslint: import/no-webpack-loader-syntax
> Why? Since using Webpack syntax in the imports couples the code to a module bundler. Prefer using the loader syntax in webpack.config.js.
javascript
1// bad 2 import fooSass from 'css!sass!foo.scss'; 3 import barCss from 'style!css!bar.css'; 4 5 // good 6 import fooSass from 'foo.scss'; 7 import barCss from 'bar.css';
10.10 Do not include JavaScript filename extensions
eslint: import/extensions
> Why? Including extensions inhibits refactoring, and inappropriately hardcodes implementation details of the module you're importing in every consumer.
javascript
1// bad 2 import foo from './foo.js'; 3 import bar from './bar.jsx'; 4 import baz from './baz/index.jsx'; 5 6 // good 7 import foo from './foo'; 8 import bar from './bar'; 9 import baz from './baz';
Iterators and Generators
11.1 Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like for-in or for-of. eslint: no-iterator no-restricted-syntax
> Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
> Use map() / every() / filter() / find() / findIndex() / reduce() / some() / ... to iterate over arrays, and Object.keys() / Object.values() / Object.entries() to produce arrays so you can iterate over objects.
javascript
1const numbers = [1, 2, 3, 4, 5]; 2 3 // bad 4 let sum = 0; 5 for (let num of numbers) { 6 sum += num; 7 } 8 sum === 15; 9 10 // good 11 let sum = 0; 12 numbers.forEach((num) => { 13 sum += num; 14 }); 15 sum === 15; 16 17 // best (use the functional force) 18 const sum = numbers.reduce((total, num) => total + num, 0); 19 sum === 15; 20 21 // bad 22 const increasedByOne = []; 23 for (let i = 0; i < numbers.length; i++) { 24 increasedByOne.push(numbers[i] + 1); 25 } 26 27 // good 28 const increasedByOne = []; 29 numbers.forEach((num) => { 30 increasedByOne.push(num + 1); 31 }); 32 33 // best (keeping it functional) 34 const increasedByOne = numbers.map((num) => num + 1);
11.2 Don’t use generators for now.
> Why? They don’t transpile well to ES5.
11.3 If you must use generators, or if you disregard our advice, make sure their function signature is spaced properly. eslint: generator-star-spacing
> Why? function and _are part of the same conceptual keyword - _ is not a modifier for function, function* is a unique construct, different from function.
javascript
1// bad 2 function * foo() { 3 // ... 4 } 5 6 // bad 7 const bar = function * () { 8 // ... 9 }; 10 11 // bad 12 const baz = function *() { 13 // ... 14 }; 15 16 // bad 17 const quux = function*() { 18 // ... 19 }; 20 21 // bad 22 function*foo() { 23 // ... 24 } 25 26 // bad 27 function *foo() { 28 // ... 29 } 30 31 // very bad 32 function 33 * 34 foo() { 35 // ... 36 } 37 38 // very bad 39 const wat = function 40 * 41 () { 42 // ... 43 }; 44 45 // good 46 function* foo() { 47 // ... 48 } 49 50 // good 51 const foo = function* () { 52 // ... 53 };
Properties
12.1 Use dot notation when accessing properties. eslint: dot-notation
javascript
1const luke = { 2 jedi: true, 3 age: 28, 4 }; 5 6 // bad 7 const isJedi = luke['jedi']; 8 9 // good 10 const isJedi = luke.jedi;
12.2 Use bracket notation [] when accessing properties with a variable.
javascript
1const luke = { 2 jedi: true, 3 age: 28, 4 }; 5 6 function getProp(prop) { 7 return luke[prop]; 8 } 9 10 const isJedi = getProp('jedi');
12.3 Use exponentiation operator ** when calculating exponentiations. eslint: prefer-exponentiation-operator.
javascript
1// bad 2 const binary = Math.pow(2, 10); 3 4 // good 5 const binary = 2 ** 10;
Variables
13.1 Always use const or let 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 prefer-const
javascript
1// bad 2 superPower = new SuperPower(); 3 4 // good 5 const superPower = new SuperPower();
13.2 Use one const or let declaration per variable or assignment. 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. You can also step through each declaration with the debugger, instead of jumping through all of them at once.
javascript
1// bad 2 const items = getItems(), 3 goSportsTeam = true, 4 dragonball = 'z'; 5 6 // bad 7 // (compare to above, and try to spot the mistake) 8 const items = getItems(), 9 goSportsTeam = true; 10 dragonball = 'z'; 11 12 // good 13 const items = getItems(); 14 const goSportsTeam = true; 15 const dragonball = 'z';
13.3 Group all your consts and then group all your lets.
> Why? This is helpful when later on you might need to assign a variable depending on one of the previously assigned variables.
javascript
1// bad 2 let i, len, dragonball, 3 items = getItems(), 4 goSportsTeam = true; 5 6 // bad 7 let i; 8 const items = getItems(); 9 let dragonball; 10 const goSportsTeam = true; 11 let len; 12 13 // good 14 const goSportsTeam = true; 15 const items = getItems(); 16 let dragonball; 17 let i; 18 let length;
13.4 Assign variables where you need them, but place them in a reasonable place.
> Why? let and const are block scoped and not function scoped.
javascript
1// bad - unnecessary function call 2 function checkName(hasName) { 3 const name = getName(); 4 5 if (hasName === 'test') { 6 return false; 7 } 8 9 if (name === 'test') { 10 this.setName(''); 11 return false; 12 } 13 14 return name; 15 } 16 17 // good 18 function checkName(hasName) { 19 if (hasName === 'test') { 20 return false; 21 } 22 23 const name = getName(); 24 25 if (name === 'test') { 26 this.setName(''); 27 return false; 28 } 29 30 return name; 31 }
13.5 Don’t chain variable assignments. eslint: no-multi-assign
> Why? Chaining variable assignments creates implicit global variables.
javascript
``1// bad 2 (function example() { 3 // JavaScript interprets this as 4 // let a = ( b = ( c = 1 ) ); 5 // The let keyword only applies to variable a; variables b and c become 6 // global variables. 7 let a = b = c = 1; 8 }()); 9 10 console.log(a); // throws ReferenceError 11 console.log(b); // 1 12 console.log(c); // 1 13 14 // good 15 (function example() { 16 let a = 1; 17 let b = a; 18 let c = a; 19 }()); 20 21 console.log(a); // throws ReferenceError 22 console.log(b); // throws ReferenceError 23 console.log(c); // throws ReferenceError 24 25 // the same applies for `const```
13.6 Avoid using unary increments and decrements (++, --). eslint no-plusplus
> Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like num += 1 instead of num++ or num ++. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs.
javascript
1// bad 2 3 const array = [1, 2, 3]; 4 let num = 1; 5 num++; 6 --num; 7 8 let sum = 0; 9 let truthyCount = 0; 10 for (let i = 0; i < array.length; i++) { 11 let value = array[i]; 12 sum += value; 13 if (value) { 14 truthyCount++; 15 } 16 } 17 18 // good 19 20 const array = [1, 2, 3]; 21 let num = 1; 22 num += 1; 23 num -= 1; 24 25 const sum = array.reduce((a, b) => a + b, 0); 26 const truthyCount = array.filter(Boolean).length;
13.7 Avoid linebreaks before or after = in an assignment. If your assignment violates max-len, surround the value in parens. eslint operator-linebreak.
> Why? Linebreaks surrounding = can obfuscate the value of an assignment.
javascript
1// bad 2 const foo = 3 superLongLongLongLongLongLongLongLongFunctionName(); 4 5 // bad 6 const foo 7 = 'superLongLongLongLongLongLongLongLongString'; 8 9 // good 10 const foo = ( 11 superLongLongLongLongLongLongLongLongFunctionName() 12 ); 13 14 // good 15 const foo = 'superLongLongLongLongLongLongLongLongString';
13.8 Disallow unused variables. eslint: no-unused-vars
> Why? Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
javascript
1// bad 2 3 const some_unused_var = 42; 4 5 // Write-only variables are not considered as used. 6 let y = 10; 7 y = 5; 8 9 // A read for a modification of itself is not considered as used. 10 let z = 0; 11 z = z + 1; 12 13 // Unused function arguments. 14 function getX(x, y) { 15 return x; 16 } 17 18 // good 19 20 function getXPlusY(x, y) { 21 return x + y; 22 } 23 24 const x = 1; 25 const y = a + 2; 26 27 alert(getXPlusY(x, y)); 28 29 // 'type' is ignored even if unused because it has a rest property sibling. 30 // This is a form of extracting an object that omits the specified keys. 31 const { type, ...coords } = data; 32 // 'coords' is now the 'data' object without its 'type' property.
Hoisting
14.1var declarations get hoisted to the top of their closest enclosing function scope, their assignment does not. const and let declarations are blessed with a new concept called Temporal Dead Zones (TDZ). It’s important to know why typeof is no longer safe.
javascript
1// we know this wouldn’t work (assuming there 2 // is no notDefined global variable) 3 function example() { 4 console.log(notDefined); // => throws a ReferenceError 5 } 6 7 // creating a variable declaration after you 8 // reference the variable will work due to 9 // variable hoisting. Note: the assignment 10 // value of `true` is not hoisted. 11 function example() { 12 console.log(declaredButNotAssigned); // => undefined 13 var declaredButNotAssigned = true; 14 } 15 16 // the interpreter is hoisting the variable 17 // declaration to the top of the scope, 18 // which means our example could be rewritten as: 19 function example() { 20 let declaredButNotAssigned; 21 console.log(declaredButNotAssigned); // => undefined 22 declaredButNotAssigned = true; 23 } 24 25 // using const and let 26 function example() { 27 console.log(declaredButNotAssigned); // => throws a ReferenceError 28 console.log(typeof declaredButNotAssigned); // => throws a ReferenceError 29 const declaredButNotAssigned = true; 30 }
14.2 Anonymous function expressions hoist their variable name, but not the function assignment.
javascript
1function example() { 2 console.log(anonymous); // => undefined 3 4 anonymous(); // => TypeError anonymous is not a function 5 6 var anonymous = function () { 7 console.log('anonymous function expression'); 8 }; 9 }
14.3 Named function expressions hoist the variable name, not the function name or the function body.
javascript
1function example() { 2 console.log(named); // => undefined 3 4 named(); // => TypeError named is not a function 5 6 superPower(); // => ReferenceError superPower is not defined 7 8 var named = function superPower() { 9 console.log('Flying'); 10 }; 11 } 12 13 // the same is true when the function name 14 // is the same as the variable name. 15 function example() { 16 console.log(named); // => undefined 17 18 named(); // => TypeError named is not a function 19 20 var named = function named() { 21 console.log('named'); 22 }; 23 }
14.4 Function declarations hoist their name and the function body.
javascript
1function example() { 2 superPower(); // => Flying 3 4 function superPower() { 5 console.log('Flying'); 6 } 7 }
14.5 Variables, classes, and functions should be defined before they can be used. eslint: no-use-before-define
> Why? When variables, classes, or functions are declared after being used, it can harm readability since a reader won't know what a thing that's referenced is. It's much clearer for a reader to first encounter the source of a thing (whether imported from another module, or defined in the file) before encountering a use of the thing.
javascript
1// bad 2 3 // Variable a is being used before it is being defined. 4 console.log(a); // this will be undefined, since while the declaration is hoisted, the initialization is not 5 var a = 10; 6 7 // Function fun is being called before being defined. 8 fun(); 9 function fun() {} 10 11 // Class A is being used before being defined. 12 new A(); // ReferenceError: Cannot access 'A' before initialization 13 class A { 14 } 15 16 // `let` and `const` are hoisted, but they don't have a default initialization. 17 // The variables 'a' and 'b' are in a Temporal Dead Zone where JavaScript 18 // knows they exist (declaration is hoisted) but they are not accessible 19 // (as they are not yet initialized). 20 21 console.log(a); // ReferenceError: Cannot access 'a' before initialization 22 console.log(b); // ReferenceError: Cannot access 'b' before initialization 23 let a = 10; 24 const b = 5; 25 26 27 // good 28 29 var a = 10; 30 console.log(a); // 10 31 32 function fun() {} 33 fun(); 34 35 class A { 36 } 37 new A(); 38 39 let a = 10; 40 const b = 5; 41 console.log(a); // 10 42 console.log(b); // 5
For more information refer to JavaScript Scoping & Hoisting by Ben Cherry.
Comparison Operators & Equality
15.1 Use === and !== over == and !=. eslint: eqeqeq
15.2 Conditional statements such as the if statement evaluate their expression using coercion with the ToBoolean abstract method and always follow these simple rules:
Objects evaluate to true
Undefined evaluates to false
Null evaluates to false
Booleans evaluate to the value of the boolean
Numbers evaluate to false if +0, -0, or NaN, otherwise true
Strings evaluate to false if an empty string '', otherwise true
javascript
1if ([0] && []) { 2 // true 3 // an array (even an empty one) is an object, objects will evaluate to true 4 }
15.3 Use shortcuts for booleans, but explicit comparisons for strings and numbers.
javascript
1// bad 2 if (isValid === true) { 3 // ... 4 } 5 6 // good 7 if (isValid) { 8 // ... 9 } 10 11 // bad 12 if (name) { 13 // ... 14 } 15 16 // good 17 if (name !== '') { 18 // ... 19 } 20 21 // bad 22 if (collection.length) { 23 // ... 24 } 25 26 // good 27 if (collection.length > 0) { 28 // ... 29 }
15.4 For more information see Truth, Equality, and JavaScript by Angus Croll.
15.5 Use braces to create blocks in case and default clauses that contain lexical declarations (e.g. let, const, function, and class). eslint: no-case-declarations
> Why? Lexical declarations are visible in the entire switch block but only get initialized when assigned, which only happens when its case is reached. This causes problems when multiple case clauses attempt to define the same thing.
javascript
1// bad 2 switch (foo) { 3 case 1: 4 let x = 1; 5 break; 6 case 2: 7 const y = 2; 8 break; 9 case 3: 10 function f() { 11 // ... 12 } 13 break; 14 default: 15 class C {} 16 } 17 18 // good 19 switch (foo) { 20 case 1: { 21 let x = 1; 22 break; 23 } 24 case 2: { 25 const y = 2; 26 break; 27 } 28 case 3: { 29 function f() { 30 // ... 31 } 32 break; 33 } 34 case 4: 35 bar(); 36 break; 37 default: { 38 class C {} 39 } 40 }
15.6 Ternaries should not be nested and generally be single line expressions. eslint: no-nested-ternary
javascript
1// bad 2 const foo = maybe1 > maybe2 3 ? 'bar' 4 : value1 > value2 ? 'baz' : null; 5 6 // split into 2 separated ternary expressions 7 const maybeNull = value1 > value2 ? 'baz' : null; 8 9 // better 10 const foo = maybe1 > maybe2 11 ? 'bar' 12 : maybeNull; 13 14 // best 15 const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
15.7 Avoid unneeded ternary statements. eslint: no-unneeded-ternary
javascript
1// bad 2 const foo = a ? a : b; 3 const bar = c ? true : false; 4 const baz = c ? false : true; 5 const quux = a != null ? a : b; 6 7 // good 8 const foo = a || b; 9 const bar = !!c; 10 const baz = !c; 11 const quux = a ?? b;
15.8 When mixing operators, enclose them in parentheses. The only exception is the standard arithmetic operators: +, -, and * since their precedence is broadly understood. We recommend enclosing / and `` in parentheses because their precedence can be ambiguous when they are mixed.
eslint: no-mixed-operators
> Why? This improves readability and clarifies the developer’s intention.
javascript
1// bad 2 const foo = a && b < 0 || c > 0 || d + 1 === 0; 3 4 // bad 5 const bar = a ** b - 5 % d; 6 7 // bad 8 // one may be confused into thinking (a || b) && c 9 if (a || b && c) { 10 return d; 11 } 12 13 // bad 14 const bar = a + b / c * d; 15 16 // good 17 const foo = (a && b < 0) || c > 0 || (d + 1 === 0); 18 19 // good 20 const bar = a ** b - (5 % d); 21 22 // good 23 if (a || (b && c)) { 24 return d; 25 } 26 27 // good 28 const bar = a + (b / c) * d;
15.9 The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined. Otherwise, it returns the left-hand side operand.
> Why? It provides precision by distinguishing null/undefined from other falsy values, enhancing code clarity and predictability.
javascript
1// bad 2 const value = 0 ?? 'default'; 3 // returns 0, not 'default' 4 5 // bad 6 const value = '' ?? 'default'; 7 // returns '', not 'default' 8 9 // good 10 const value = null ?? 'default'; 11 // returns 'default' 12 13 // good 14 const user = { 15 name: 'John', 16 age: null 17 }; 18 const age = user.age ?? 18; 19 // returns 18
Blocks
16.1 Use braces with all multiline blocks. eslint: nonblock-statement-body-position
javascript
1// bad 2 if (test) 3 return false; 4 5 // good 6 if (test) return false; 7 8 // good 9 if (test) { 10 return false; 11 } 12 13 // bad 14 function foo() { return false; } 15 16 // good 17 function bar() { 18 return false; 19 }
16.2 If you’re using multiline blocks with if and else, put else on the same line as your if block’s closing brace. eslint: brace-style
javascript
1// bad 2 if (test) { 3 thing1(); 4 thing2(); 5 } 6 else { 7 thing3(); 8 } 9 10 // good 11 if (test) { 12 thing1(); 13 thing2(); 14 } else { 15 thing3(); 16 }
16.3 If an if block always executes a return statement, the subsequent else block is unnecessary. A return in an else if block following an if block that contains a return can be separated into multiple if blocks. eslint: no-else-return
javascript
1// bad 2 function foo() { 3 if (x) { 4 return x; 5 } else { 6 return y; 7 } 8 } 9 10 // bad 11 function cats() { 12 if (x) { 13 return x; 14 } else if (y) { 15 return y; 16 } 17 } 18 19 // bad 20 function dogs() { 21 if (x) { 22 return x; 23 } else { 24 if (y) { 25 return y; 26 } 27 } 28 } 29 30 // good 31 function foo() { 32 if (x) { 33 return x; 34 } 35 36 return y; 37 } 38 39 // good 40 function cats() { 41 if (x) { 42 return x; 43 } 44 45 if (y) { 46 return y; 47 } 48 } 49 50 // good 51 function dogs(x) { 52 if (x) { 53 if (z) { 54 return y; 55 } 56 } else { 57 return z; 58 } 59 }
Control Statements
17.1 In case your control statement (if, while etc.) gets too long or exceeds the maximum line length, each (grouped) condition could be put into a new line. The logical operator should begin the line.
> Why? Requiring operators at the beginning of the line keeps the operators aligned and follows a pattern similar to method chaining. This also improves readability by making it easier to visually follow complex logic.
javascript
1// bad 2 if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) { 3 thing1(); 4 } 5 6 // bad 7 if (foo === 123 && 8 bar === 'abc') { 9 thing1(); 10 } 11 12 // bad 13 if (foo === 123 14 && bar === 'abc') { 15 thing1(); 16 } 17 18 // bad 19 if ( 20 foo === 123 && 21 bar === 'abc' 22 ) { 23 thing1(); 24 } 25 26 // good 27 if ( 28 foo === 123 29 && bar === 'abc' 30 ) { 31 thing1(); 32 } 33 34 // good 35 if ( 36 (foo === 123 || bar === 'abc') 37 && doesItLookGoodWhenItBecomesThatLong() 38 && isThisReallyHappening() 39 ) { 40 thing1(); 41 } 42 43 // good 44 if (foo === 123 && bar === 'abc') { 45 thing1(); 46 }
17.2 Don't use selection operators in place of control statements.
javascript
1// bad 2 !isRunning && startRunning(); 3 4 // good 5 if (!isRunning) { 6 startRunning(); 7 }
Comments
18.1 Use /* ... / for multiline comments.
javascript
1// bad 2 // make() returns a new element 3 // based on the passed in tag name 4 // 5 // @param {String} tag 6 // @return {Element} element 7 function make(tag) { 8 9 // ... 10 11 return element; 12 } 13 14 // good 15 /** 16 * make() returns a new element 17 * based on the passed-in tag name 18 */ 19 function make(tag) { 20 21 // ... 22 23 return element; 24 }
18.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.
javascript
1// bad 2 const active = true; // is current tab 3 4 // good 5 // is current tab 6 const active = true; 7 8 // bad 9 function getType() { 10 console.log('fetching type...'); 11 // set the default type to 'no type' 12 const type = this.type || 'no type'; 13 14 return type; 15 } 16 17 // good 18 function getType() { 19 console.log('fetching type...'); 20 21 // set the default type to 'no type' 22 const type = this.type || 'no type'; 23 24 return type; 25 } 26 27 // also good 28 function getType() { 29 // set the default type to 'no type' 30 const type = this.type || 'no type'; 31 32 return type; 33 }
18.3 Start all comments with a space to make it easier to read. eslint: spaced-comment
javascript
1// bad 2 //is current tab 3 const active = true; 4 5 // good 6 // is current tab 7 const active = true; 8 9 // bad 10 /** 11 *make() returns a new element 12 *based on the passed-in tag name 13 */ 14 function make(tag) { 15 16 // ... 17 18 return element; 19 } 20 21 // good 22 /** 23 * make() returns a new element 24 * based on the passed-in tag name 25 */ 26 function make(tag) { 27 28 // ... 29 30 return element; 31 }
18.4 Prefixing your comments with FIXME or TODO 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. The actions are FIXME: -- need to figure this out or TODO: -- need to implement.
18.5 Use // FIXME: to annotate problems.
javascript
1class Calculator extends Abacus { 2 constructor() { 3 super(); 4 5 // FIXME: shouldn’t use a global here 6 total = 0; 7 } 8 }
18.6 Use // TODO: to annotate solutions to problems.
javascript
1class Calculator extends Abacus { 2 constructor() { 3 super(); 4 5 // TODO: total should be configurable by an options param 6 this.total = 0; 7 } 8 }
Whitespace
19.1 Use soft tabs (space character) set to 2 spaces. eslint: indent
javascript
1// bad 2 function foo() { 3 ∙∙∙∙let name; 4 } 5 6 // bad 7 function bar() { 8 ∙let name; 9 } 10 11 // good 12 function baz() { 13 ∙∙let name; 14 }
19.2 Place 1 space before the leading brace. eslint: space-before-blocks
javascript
1// bad 2 function test(){ 3 console.log('test'); 4 } 5 6 // good 7 function test() { 8 console.log('test'); 9 } 10 11 // bad 12 dog.set('attr',{ 13 age: '1 year', 14 breed: 'Bernese Mountain Dog', 15 }); 16 17 // good 18 dog.set('attr', { 19 age: '1 year', 20 breed: 'Bernese Mountain Dog', 21 });
19.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
javascript
1// bad 2 if(isJedi) { 3 fight (); 4 } 5 6 // good 7 if (isJedi) { 8 fight(); 9 } 10 11 // bad 12 function fight () { 13 console.log ('Swooosh!'); 14 } 15 16 // good 17 function fight() { 18 console.log('Swooosh!'); 19 }
19.4 Set off operators with spaces. eslint: space-infix-ops
javascript
1// bad 2 const x=y+5; 3 4 // good 5 const x = y + 5;
19.5 End files with a single newline character. eslint: eol-last
javascript
1// bad 2 import { es6 } from './AirbnbStyleGuide'; 3 // ... 4 export default es6;
javascript
1// bad 2 import { es6 } from './AirbnbStyleGuide'; 3 // ... 4 export default es6;↵ 5 ↵
javascript
1// good 2 import { es6 } from './AirbnbStyleGuide'; 3 // ... 4 export default es6;↵
19.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 no-whitespace-before-property
javascript
1// bad 2 $('#items').find('.selected').highlight().end().find('.open').updateCount(); 3 4 // bad 5 $('#items'). 6 find('.selected'). 7 highlight(). 8 end(). 9 find('.open'). 10 updateCount(); 11 12 // good 13 $('#items') 14 .find('.selected') 15 .highlight() 16 .end() 17 .find('.open') 18 .updateCount(); 19 20 // bad 21 const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true) 22 .attr('width', (radius + margin) * 2).append('svg:g') 23 .attr('transform', `translate(${radius + margin}, ${radius + margin})`) 24 .call(tron.led); 25 26 // good 27 const leds = stage.selectAll('.led') 28 .data(data) 29 .enter().append('svg:svg') 30 .classed('led', true) 31 .attr('width', (radius + margin) * 2) 32 .append('svg:g') 33 .attr('transform', `translate(${radius + margin}, ${radius + margin})`) 34 .call(tron.led); 35 36 // good 37 const leds = stage.selectAll('.led').data(data); 38 const svg = leds.enter().append('svg:svg'); 39 svg.classed('led', true).attr('width', (radius + margin) * 2); 40 const g = svg.append('svg:g'); 41 g.attr('transform', `translate(${radius + margin}, ${radius + margin})`).call(tron.led);
19.7 Leave a blank line after blocks and before the next statement.
javascript
1// bad 2 if (foo) { 3 return bar; 4 } 5 return baz; 6 7 // good 8 if (foo) { 9 return bar; 10 } 11 12 return baz; 13 14 // bad 15 const obj = { 16 foo() { 17 }, 18 bar() { 19 }, 20 }; 21 return obj; 22 23 // good 24 const obj = { 25 foo() { 26 }, 27 28 bar() { 29 }, 30 }; 31 32 return obj; 33 34 // bad 35 const arr = [\ 36 function foo() {\ 37 },\ 38 function bar() {\ 39 },\ 40 ]; 41 return arr; 42 43 // good 44 const arr = [\ 45 function foo() {\ 46 },\ 47\ 48 function bar() {\ 49 },\ 50 ]; 51 52 return arr;
19.8 Do not pad your blocks with blank lines. eslint: padded-blocks
javascript
1// bad 2 function bar() { 3 4 console.log(foo); 5 6 } 7 8 // bad 9 if (baz) { 10 11 console.log(quux); 12 } else { 13 console.log(foo); 14 15 } 16 17 // bad 18 class Foo { 19 20 constructor(bar) { 21 this.bar = bar; 22 } 23 } 24 25 // good 26 function bar() { 27 console.log(foo); 28 } 29 30 // good 31 if (baz) { 32 console.log(quux); 33 } else { 34 console.log(foo); 35 }
19.9 Do not use multiple blank lines to pad your code. eslint: no-multiple-empty-lines
javascript
1// bad 2 class Person { 3 constructor(fullName, email, birthday) { 4 this.fullName = fullName; 5 6 7 this.email = email; 8 9 10 this.setAge(birthday); 11 } 12 13 14 setAge(birthday) { 15 const today = new Date(); 16 17 18 const age = this.getAge(today, birthday); 19 20 21 this.age = age; 22 } 23 24 25 getAge(today, birthday) { 26 // .. 27 } 28 } 29 30 // good 31 class Person { 32 constructor(fullName, email, birthday) { 33 this.fullName = fullName; 34 this.email = email; 35 this.setAge(birthday); 36 } 37 38 setAge(birthday) { 39 const today = new Date(); 40 const age = getAge(today, birthday); 41 this.age = age; 42 } 43 44 getAge(today, birthday) { 45 // .. 46 } 47 }
19.10 Do not add spaces inside parentheses. eslint: space-in-parens
javascript
1// bad 2 function bar( foo ) { 3 return foo; 4 } 5 6 // good 7 function bar(foo) { 8 return foo; 9 } 10 11 // bad 12 if ( foo ) { 13 console.log(foo); 14 } 15 16 // good 17 if (foo) { 18 console.log(foo); 19 }
19.11 Do not add spaces inside brackets. eslint: array-bracket-spacing
javascript
1// bad 2 const foo = [ 1, 2, 3 ]; 3 console.log(foo[ 0 ]); 4 5 // good 6 const foo = [1, 2, 3]; 7 console.log(foo[0]);
19.12 Add spaces inside curly braces. eslint: object-curly-spacing
javascript
1// bad 2 const foo = {clark: 'kent'}; 3 4 // good 5 const foo = { clark: 'kent' };
19.13 Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per above, long strings are exempt from this rule, and should not be broken up. eslint: max-len
> Why? This ensures readability and maintainability.
javascript
1// bad 2 const foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy; 3 4 // bad 5 $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.')); 6 7 // good 8 const foo = jsonData 9 && jsonData.foo 10 && jsonData.foo.bar 11 && jsonData.foo.bar.baz 12 && jsonData.foo.bar.baz.quux 13 && jsonData.foo.bar.baz.quux.xyzzy; 14 15 // better 16 const foo = jsonData 17 ?.foo 18 ?.bar 19 ?.baz 20 ?.quux 21 ?.xyzzy; 22 23 // good 24 $.ajax({ 25 method: 'POST', 26 url: 'https://airbnb.com/', 27 data: { name: 'John' }, 28 }) 29 .done(() => console.log('Congratulations!')) 30 .fail(() => console.log('You have failed this city.'));
19.14 Require consistent spacing inside an open block token and the next token on the same line. This rule also enforces consistent spacing inside a close block token and previous token on the same line. eslint: block-spacing
javascript
1// bad 2 function foo() {return true;} 3 if (foo) { bar = 0;} 4 5 // good 6 function foo() { return true; } 7 if (foo) { bar = 0; }
19.15 Avoid spaces before commas and require a space after commas. eslint: comma-spacing
javascript
1// bad 2 const foo = 1,bar = 2; 3 const arr = [1 , 2]; 4 5 // good 6 const foo = 1, bar = 2; 7 const arr = [1, 2];
19.16 Enforce spacing inside of computed property brackets. eslint: computed-property-spacing
javascript
1// bad 2 obj[foo ] 3 obj[ 'foo'] 4 const x = {[ b ]: a} 5 obj[foo[ bar ]] 6 7 // good 8 obj[foo] 9 obj['foo'] 10 const x = { [b]: a } 11 obj[foo[bar]]
19.17 Avoid spaces between functions and their invocations. eslint: func-call-spacing
javascript
1// bad 2 func (); 3 4 func 5 (); 6 7 // good 8 func();
19.18 Enforce spacing between keys and values in object literal properties. eslint: key-spacing
javascript
1// bad 2 const obj = { foo : 42 }; 3 const obj2 = { foo:42 }; 4 5 // good 6 const obj = { foo: 42 };
19.19 Avoid trailing spaces at the end of lines. eslint: no-trailing-spaces
19.20 Avoid multiple empty lines, only allow one newline at the end of files, and avoid a newline at the beginning of files. eslint: no-multiple-empty-lines
javascript
1// bad - multiple empty lines 2 const x = 1; 3 4 5 const y = 2; 6 7 // bad - 2+ newlines at end of file 8 const x = 1; 9 const y = 2; 10 11 12 // bad - 1+ newline(s) at beginning of file 13 14 const x = 1; 15 const y = 2; 16 17 // good 18 const x = 1; 19 const y = 2;
Commas
20.1 Leading commas: Nope. eslint: comma-style
javascript
1// bad 2 const story = [\ 3 once\ 4 , upon\ 5 , aTime\ 6 ]; 7 8 // good 9 const story = [\ 10 once,\ 11 upon,\ 12 aTime,\ 13 ]; 14 15 // bad 16 const hero = { 17 firstName: 'Ada' 18 , lastName: 'Lovelace' 19 , birthYear: 1815 20 , superPower: 'computers' 21 }; 22 23 // good 24 const hero = { 25 firstName: 'Ada', 26 lastName: 'Lovelace', 27 birthYear: 1815, 28 superPower: 'computers', 29 };
20.2 Additional trailing comma: Yup. eslint: comma-dangle
> Why? This leads to cleaner git diffs. Also, transpilers like Babel will remove the additional trailing comma in the transpiled code which means you don’t have to worry about the trailing comma problem in legacy browsers.
diff
1// bad - git diff without trailing comma 2 const hero = { 3 firstName: 'Florence', 4 - lastName: 'Nightingale' 5 + lastName: 'Nightingale', 6 + inventorOf: ['coxcomb chart', 'modern nursing'] 7 }; 8 9 // good - git diff with trailing comma 10 const hero = { 11 firstName: 'Florence', 12 lastName: 'Nightingale', 13 + inventorOf: ['coxcomb chart', 'modern nursing'], 14 };
javascript
1// bad 2 const hero = { 3 firstName: 'Dana', 4 lastName: 'Scully' 5 }; 6 7 const heroes = [\ 8 'Batman',\ 9 'Superman'\ 10 ]; 11 12 // good 13 const hero = { 14 firstName: 'Dana', 15 lastName: 'Scully', 16 }; 17 18 const heroes = [\ 19 'Batman',\ 20 'Superman',\ 21 ]; 22 23 // bad 24 function createHero( 25 firstName, 26 lastName, 27 inventorOf 28 ) { 29 // does nothing 30 } 31 32 // good 33 function createHero( 34 firstName, 35 lastName, 36 inventorOf, 37 ) { 38 // does nothing 39 } 40 41 // good (note that a comma must not appear after a "rest" element) 42 function createHero( 43 firstName, 44 lastName, 45 inventorOf, 46 ...heroArgs 47 ) { 48 // does nothing 49 } 50 51 // bad 52 createHero( 53 firstName, 54 lastName, 55 inventorOf 56 ); 57 58 // good 59 createHero( 60 firstName, 61 lastName, 62 inventorOf, 63 ); 64 65 // good (note that a comma must not appear after a "rest" element) 66 createHero( 67 firstName, 68 lastName, 69 inventorOf, 70 ...heroArgs 71 );
Semicolons
> Why? When JavaScript encounters a line break without a semicolon, it uses a set of rules called Automatic Semicolon Insertion to determine whether it should regard that line break as the end of a statement, and (as the name implies) place a semicolon into your code before the line break if it thinks so. ASI contains a few eccentric behaviors, though, and your code will break if JavaScript misinterprets your line break. These rules will become more complicated as new features become a part of JavaScript. Explicitly terminating your statements and configuring your linter to catch missing semicolons will help prevent you from encountering issues.
javascript
1// bad - raises exception 2 const luke = {} 3 const leia = {} 4 [luke, leia].forEach((jedi) => jedi.father = 'vader') 5 6 // bad - raises exception 7 const reaction = "No! That’s impossible!" 8 (async function meanwhileOnTheFalcon() { 9 // handle `leia`, `lando`, `chewie`, `r2`, `c3p0` 10 // ... 11 }()) 12 13 // bad - returns `undefined` instead of the value on the next line - always happens when `return` is on a line by itself because of ASI! 14 function foo() { 15 return 16 'search your feelings, you know it to be foo' 17 } 18 19 // good 20 const luke = {}; 21 const leia = {}; 22 [luke, leia].forEach((jedi) => { 23 jedi.father = 'vader'; 24 }); 25 26 // good 27 const reaction = 'No! That’s impossible!'; 28 (async function meanwhileOnTheFalcon() { 29 // handle `leia`, `lando`, `chewie`, `r2`, `c3p0` 30 // ... 31 }()); 32 33 // good 34 function foo() { 35 return 'search your feelings, you know it to be foo'; 36 }
Type Casting & Coercion
22.1 Perform type coercion at the beginning of the statement.
22.2 Strings: eslint: no-new-wrappers
javascript
1// => this.reviewScore = 9; 2 3 // bad 4 const totalScore = new String(this.reviewScore); // typeof totalScore is "object" not "string" 5 6 // bad 7 const totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf() 8 9 // bad 10 const totalScore = this.reviewScore.toString(); // isn’t guaranteed to return a string 11 12 // good 13 const totalScore = String(this.reviewScore);
22.3 Numbers: Use Number for type casting and parseInt always with a radix for parsing strings. eslint: radix no-new-wrappers
> Why? The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading whitespace in string is ignored. If radix is undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix of 16 is assumed. This differs from ECMAScript 3, which merely discouraged (but allowed) octal interpretation. Many implementations have not adopted this behavior as of 2013. And, because older browsers must be supported, always specify a radix.
javascript
1const inputValue = '4'; 2 3 // bad 4 const val = new Number(inputValue); 5 6 // bad 7 const val = +inputValue; 8 9 // bad 10 const val = inputValue >> 0; 11 12 // bad 13 const val = parseInt(inputValue); 14 15 // good 16 const val = Number(inputValue); 17 18 // good 19 const val = parseInt(inputValue, 10);
22.4 If for whatever reason you are doing something wild and parseInt is your bottleneck and need to use Bitshift for performance reasons, leave a comment explaining why and what you’re doing.
javascript
1// good 2 /** 3 * parseInt was the reason my code was slow. 4 * Bitshifting the String to coerce it to a 5 * Number made it a lot faster. 6 */ 7 const val = inputValue >> 0;
22.5 Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values, but bitshift operations always return a 32-bit integer ( source). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion. Largest signed 32-bit Int is 2,147,483,647:
javascript
12147483647 >> 0; // => 2147483647 2 2147483648 >> 0; // => -2147483648 3 2147483649 >> 0; // => -2147483647
22.6 Booleans: eslint: no-new-wrappers
javascript
1const age = 0; 2 3 // bad 4 const hasAge = new Boolean(age); 5 6 // good 7 const hasAge = Boolean(age); 8 9 // best 10 const hasAge = !!age;
Naming Conventions
23.1 Avoid single letter names. Be descriptive with your naming. eslint: id-length
javascript
1// bad 2 function q() { 3 // ... 4 } 5 6 // good 7 function query() { 8 // ... 9 }
23.2 Use camelCase when naming objects, functions, and instances. eslint: camelcase
javascript
1// bad 2 const OBJEcttsssss = {}; 3 const this_is_my_object = {}; 4 function c() {} 5 6 // good 7 const thisIsMyObject = {}; 8 function thisIsMyFunction() {}
23.3 Use PascalCase only when naming constructors or classes. eslint: new-cap
javascript
1// bad 2 function user(options) { 3 this.name = options.name; 4 } 5 6 const bad = new user({ 7 name: 'nope', 8 }); 9 10 // good 11 class User { 12 constructor(options) { 13 this.name = options.name; 14 } 15 } 16 17 const good = new User({ 18 name: 'yup', 19 });
23.4 Do not use trailing or leading underscores. eslint: no-underscore-dangle
> Why? JavaScript does not have the concept of privacy in terms of properties or methods. Although a leading underscore is a common convention to mean “private”, in fact, these properties are fully public, and as such, are part of your public API contract. This convention might lead developers to wrongly think that a change won’t count as breaking, or that tests aren’t needed. tl;dr: if you want something to be “private”, it must not be observably present.
javascript
1// bad 2 this.__firstName__ = 'Panda'; 3 this.firstName_ = 'Panda'; 4 this._firstName = 'Panda'; 5 6 // good 7 this.firstName = 'Panda'; 8 9 // good, in environments where WeakMaps are available 10 // see https://compat-table.github.io/compat-table/es6/#test-WeakMap 11 const firstNames = new WeakMap(); 12 firstNames.set(this, 'Panda');
23.5 Don’t save references to this. Use arrow functions or Function#bind.
javascript
1// bad 2 function foo() { 3 const self = this; 4 return function () { 5 console.log(self); 6 }; 7 } 8 9 // bad 10 function foo() { 11 const that = this; 12 return function () { 13 console.log(that); 14 }; 15 } 16 17 // good 18 function foo() { 19 return () => { 20 console.log(this); 21 }; 22 }
23.6 A base filename should exactly match the name of its default export.
javascript
1// file 1 contents 2 class CheckBox { 3 // ... 4 } 5 export default CheckBox; 6 7 // file 2 contents 8 export default function fortyTwo() { return 42; } 9 10 // file 3 contents 11 export default function insideDirectory() {} 12 13 // in some other file 14 // bad 15 import CheckBox from './checkBox'; // PascalCase import/export, camelCase filename 16 import FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase export 17 import InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export 18 19 // bad 20 import CheckBox from './check_box'; // PascalCase import/export, snake_case filename 21 import forty_two from './forty_two'; // snake_case import/filename, camelCase export 22 import inside_directory from './inside_directory'; // snake_case import, camelCase export 23 import index from './inside_directory/index'; // requiring the index file explicitly 24 import insideDirectory from './insideDirectory/index'; // requiring the index file explicitly 25 26 // good 27 import CheckBox from './CheckBox'; // PascalCase export/import/filename 28 import fortyTwo from './fortyTwo'; // camelCase export/import/filename 29 import insideDirectory from './insideDirectory'; // camelCase export/import/directory name/implicit "index" 30 // ^ supports both insideDirectory.js and insideDirectory/index.js
23.7 Use camelCase when you export-default a function. Your filename should be identical to your function’s name.
javascript
1function makeStyleGuide() { 2 // ... 3 } 4 5 export default makeStyleGuide;
23.8 Use PascalCase when you export a constructor / class / singleton / function library / bare object.
javascript
1const AirbnbStyleGuide = { 2 es6: { 3 }, 4 }; 5 6 export default AirbnbStyleGuide;
23.9 Acronyms and initialisms should always be all uppercased, or all lowercased.
> Why? Names are for readability, not to appease a computer algorithm.
javascript
1// bad 2 import SmsContainer from './containers/SmsContainer'; 3 4 // bad 5 const HttpRequests = [\ 6 // ...\ 7 ]; 8 9 // good 10 import SMSContainer from './containers/SMSContainer'; 11 12 // good 13 const HTTPRequests = [\ 14 // ...\ 15 ]; 16 17 // also good 18 const httpRequests = [\ 19 // ...\ 20 ]; 21 22 // best 23 import TextMessageContainer from './containers/TextMessageContainer'; 24 25 // best 26 const requests = [\ 27 // ...\ 28 ];
23.10 You may optionally uppercase a constant only if it (1) is exported, (2) is a const (it can not be reassigned), and (3) the programmer can trust it (and its nested properties) to never change.
> Why? This is an additional tool to assist in situations where the programmer would be unsure if a variable might ever change. UPPERCASE_VARIABLES are letting the programmer know that they can trust the variable (and its properties) not to change.
What about all const variables? - This is unnecessary, so uppercasing should not be used for constants within a file. It should be used for exported constants however.
What about exported objects? - Uppercase at the top level of export (e.g. EXPORTED_OBJECT.key) and maintain that all nested properties do not change.
javascript
1// bad 2 const PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file'; 3 4 // bad 5 export const THING_TO_BE_CHANGED = 'should obviously not be uppercased'; 6 7 // bad 8 export let REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables'; 9 10 // --- 11 12 // allowed but does not supply semantic value 13 export const apiKey = 'SOMEKEY'; 14 15 // better in most cases 16 export const API_KEY = 'SOMEKEY'; 17 18 // --- 19 20 // bad - unnecessarily uppercases key while adding no semantic value 21 export const MAPPING = { 22 KEY: 'value' 23 }; 24 25 // good 26 export const MAPPING = { 27 key: 'value', 28 };
Accessors
24.1 Accessor functions for properties are not required.
24.2 Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use getVal() and setVal('hello').
javascript
1// bad 2 class Dragon { 3 get age() { 4 // ... 5 } 6 7 set age(value) { 8 // ... 9 } 10 } 11 12 // good 13 class Dragon { 14 getAge() { 15 // ... 16 } 17 18 setAge(value) { 19 // ... 20 } 21 }
24.3 If the property/method is a boolean, use isVal() or hasVal().
javascript
1// bad 2 if (!dragon.age()) { 3 return false; 4 } 5 6 // good 7 if (!dragon.hasAge()) { 8 return false; 9 }
24.4 It’s okay to create get() and set() functions, but be consistent.
javascript
1class Jedi { 2 constructor(options = {}) { 3 const lightsaber = options.lightsaber || 'blue'; 4 this.set('lightsaber', lightsaber); 5 } 6 7 set(key, val) { 8 this[key] = val; 9 } 10 11 get(key) { 12 return this[key]; 13 } 14 }
Events
25.1 When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass an object literal (also known as 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:
javascript
1// bad 2 $(this).trigger('listingUpdated', listing.id); 3 4 // ... 5 6 $(this).on('listingUpdated', (e, listingID) => { 7 // do something with listingID 8 });
prefer:
javascript
1// good 2 $(this).trigger('listingUpdated', { listingID: listing.id }); 3 4 // ... 5 6 $(this).on('listingUpdated', (e, data) => { 7 // do something with data.listingID 8 });
jQuery
26.1 Prefix jQuery object variables with a $.
javascript
1// bad 2 const sidebar = $('.sidebar'); 3 4 // good 5 const $sidebar = $('.sidebar'); 6 7 // good 8 const $sidebarBtn = $('.sidebar-btn');
26.2 Cache jQuery lookups.
javascript
1// bad 2 function setSidebar() { 3 $('.sidebar').hide(); 4 5 // ... 6 7 $('.sidebar').css({ 8 'background-color': 'pink', 9 }); 10 } 11 12 // good 13 function setSidebar() { 14 const $sidebar = $('.sidebar'); 15 $sidebar.hide(); 16 17 // ... 18 19 $sidebar.css({ 20 'background-color': 'pink', 21 }); 22 }
26.3 For DOM queries use Cascading $('.sidebar ul') or parent > child $('.sidebar > ul'). jsPerf
26.4 Use find with scoped jQuery object queries.
javascript
1// bad 2 $('ul', '.sidebar').hide(); 3 4 // bad 5 $('.sidebar').find('ul').hide(); 6 7 // good 8 $('.sidebar ul').hide(); 9 10 // good 11 $('.sidebar > ul').hide(); 12 13 // good 14 $sidebar.find('ul').hide();
ECMAScript 5 Compatibility
27.1 Refer to Kangax’s ES5 compatibility table.
ECMAScript 6+ (ES 2015+) Styles
28.1 This is a collection of links to the various ES6+ features.
28.2 Do not use TC39 proposals that have not reached stage 3.
> Why? They are not finalized, and they are subject to change or to be withdrawn entirely. We want to use JavaScript, and proposals are not JavaScript yet.
Standard Library
The Standard Library
contains utilities that are functionally broken but remain for legacy reasons.
29.1 Use Number.isNaN instead of global isNaN.
eslint: no-restricted-globals
> Why? The global isNaN coerces non-numbers to numbers, returning true for anything that coerces to NaN.
> If this behavior is desired, make it explicit.
javascript
1// bad 2 isNaN('1.2'); // false 3 isNaN('1.2.3'); // true 4 5 // good 6 Number.isNaN('1.2.3'); // false 7 Number.isNaN(Number('1.2.3')); // true
29.2 Use Number.isFinite instead of global isFinite.
eslint: no-restricted-globals
> Why? The global isFinite coerces non-numbers to numbers, returning true for anything that coerces to a finite number.
> If this behavior is desired, make it explicit.
javascript
1// bad 2 isFinite('2e3'); // true 3 4 // good 5 Number.isFinite('2e3'); // false 6 Number.isFinite(parseInt('2e3', 10)); // true
Testing
30.1 Yup.
javascript
1function foo() { 2 return true; 3 }
30.2 No, but seriously:
Whichever testing framework you use, you should be writing tests!
Strive to write many small pure functions, and minimize where mutations occur.
Be cautious about stubs and mocks - they can make your tests more brittle.
We primarily use mocha and jest at Airbnb. tape is also used occasionally for small, separate modules.
100% test coverage is a good goal to strive for, even if it’s not always practical to reach it.
Whenever you fix a bug, write a regression test. A bug fixed without a regression test is almost certainly going to break again in the future.
Performance
jQuery Find vs Context, Selector
innerHTML vs textContent for script text
Are JavaScript functions like map(), reduce(), and filter() optimized for traversing arrays?
Loading...
Resources
Learning ES6+
Comprehensive Overview of ES6 Features
Read This
Tools
Code Style Linters
ESlint - Airbnb Style .eslintrc
JSHint - Airbnb Style .jshintrc
Neutrino Preset - @neutrinojs/airbnb
Other Style Guides
Google JavaScript Style Guide (Old)
Principles of Writing Consistent, Idiomatic JavaScript
Other Styles
Naming this in nested functions - Christian Johansen
Conditional Callbacks - Ross Allen
Popular JavaScript Coding Conventions on GitHub - JeongHoon Byun
Multiple var statements in JavaScript, not superfluous - Ben Alman
Further Reading
Understanding JavaScript Closures - Angus Croll
Basic JavaScript for the impatient programmer - Dr. Axel Rauschmayer
You Might Not Need jQuery - Zack Bloom & Adam Schwartz
ES6 Features - Luke Hoban
Frontend Guidelines - Benjamin De Cock
Books
JavaScript: The Good Parts - Douglas Crockford
JavaScript Patterns - Stoyan Stefanov
Pro JavaScript Design Patterns - Ross Harmes and Dustin Diaz
High Performance Web Sites: Essential Knowledge for Front-End Engineers - Steve Souders
Maintainable JavaScript - Nicholas C. Zakas
JavaScript Web Applications - Alex MacCaw
Pro JavaScript Techniques - John Resig
Smashing Node.js: JavaScript Everywhere - Guillermo Rauch
Secrets of the JavaScript Ninja - John Resig and Bear Bibeault
Human JavaScript - Henrik Joreteg
Superhero.js - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy
JSBooks - Julien Bouquillon
Third Party JavaScript - Ben Vinegar and Anton Kovalyov
Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript - David Herman
Eloquent JavaScript - Marijn Haverbeke
You Don’t Know JS: ES6 & Beyond - Kyle Simpson
Blogs
Podcasts
In the Wild
This is a list of organizations that are using this style guide. Send us a pull request and we'll add you to the list.
123erfasst: 123erfasst/javascript
4Catalyzer: 4Catalyzer/javascript
Aan Zee: AanZee/javascript
Airbnb: airbnb/javascript
AloPeyk: AloPeyk
AltSchool: AltSchool/javascript
Apartmint: apartmint/javascript
Ascribe: ascribe/javascript
Avant: avantcredit/javascript
Axept: axept/javascript
Billabong: billabong/javascript
Bisk: bisk
Brainshark: brainshark/javascript
CaseNine: CaseNine/javascript
Cerner: Cerner
Chartboost: ChartBoost/javascript-style-guide
Coeur d'Alene Tribe: www.cdatribe-nsn.gov
ComparaOnline: comparaonline/javascript
Compass Learning: compasslearning/javascript-style-guide
DailyMotion: dailymotion/javascript
DoSomething: DoSomething/eslint-config
Digitpaint digitpaint/javascript
Drupal: www.drupal.org
Ecosia: ecosia/javascript
Evolution Gaming: evolution-gaming/javascript
EvozonJs: evozonjs/javascript
ExactTarget: ExactTarget/javascript
Flexberry: Flexberry/javascript-style-guide
Gawker Media: gawkermedia
General Electric: GeneralElectric/javascript
Generation Tux: GenerationTux/javascript
GoodData: gooddata/gdc-js-style
GreenChef: greenchef/javascript
Grooveshark: grooveshark/javascript
Grupo-Abraxas: Grupo-Abraxas/javascript
Happeo: happeo/javascript
How About We: howaboutwe/javascript
HubSpot: HubSpot/javascript
Hyper: hyperoslo/javascript-playbook
ILIAS: ILIAS
InterCity Group: intercitygroup/javascript-style-guide
Jam3: Jam3/Javascript-Code-Conventions
JSSolutions: JSSolutions/javascript
Kaplan Komputing: kaplankomputing/javascript
KickorStick: kickorstick
Kinetica Solutions: kinetica/javascript
LEINWAND: LEINWAND/javascript
Lonely Planet: lonelyplanet/javascript
M2GEN: M2GEN/javascript
Mighty Spring: mightyspring/javascript
MinnPost: MinnPost/javascript
MitocGroup: MitocGroup/javascript
Muber: muber
National Geographic Society: natgeosociety
NullDev: NullDevCo/JavaScript-Styleguide
Nulogy: nulogy/javascript
Orange Hill Development: orangehill/javascript
Orion Health: orionhealth/javascript
Peerby: Peerby/javascript
Pier 1: Pier1/javascript
Qotto: Qotto/javascript-style-guide
React: reactjs.org/docs/how-to-contribute.html#style-guide
Ripple: ripple/javascript-style-guide
Sainsbury’s Supermarkets: jsainsburyplc
Shutterfly: shutterfly/javascript
Sourcetoad: sourcetoad/javascript
Springload: springload
StratoDem Analytics: stratodem/javascript
SteelKiwi Development: steelkiwi/javascript
StudentSphere: studentsphere/javascript
SwoopApp: swoopapp/javascript
SysGarage: sysgarage/javascript-style-guide
Syzygy Warsaw: syzygypl/javascript
Target: target/javascript
Terra: terra
TheLadders: TheLadders/javascript
The Nerdery: thenerdery/javascript-standards
Tomify: tomprats
Traitify: traitify/eslint-config-traitify
T4R Technology: T4R-Technology/javascript
UrbanSim: urbansim
VoxFeed: VoxFeed/javascript-style-guide
WeBox Studio: weboxstudio/javascript
Weggo: Weggo/javascript
Zillow: zillow/javascript
Zit Software: zit-software/javascript
ZocDoc: ZocDoc/javascript
Translation
This style guide is also available in other languages:
Brazilian Portuguese: armoucar/javascript-style-guide
Bulgarian: borislavvv/javascript
Catalan: fpmweb/javascript-style-guide
Chinese (Simplified): lin-123/javascript
Chinese (Traditional): jigsawye/javascript
French: nmussy/javascript-style-guide
German: timofurrer/javascript-style-guide
Italian: sinkswim/javascript-style-guide
Japanese: mitsuruog/javascript-style-guide
Korean: ParkSB/javascript-style-guide
Russian: leonidlebedev/javascript-airbnb
Spanish: paolocarrasco/javascript-style-guide
Thai: lvarayut/javascript-style-guide
Turkish: eraycetinay/javascript
Ukrainian: ivanzusko/javascript
Vietnam: dangkyokhoang/javascript-style-guide
The JavaScript Style Guide Guide
Chat With Us About JavaScript
Find us on gitter.
Contributors
License
(The MIT License)
Copyright (c) 2012 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.
Amendments
We encourage you to fork this guide and change the rules to fit your team’s style guide. Below, you may list some amendments to the style guide. This allows you to periodically update your style guide without having to deal with merge conflicts.
};
On this page