Gathering detailed insights and metrics for eslint-config-airbnb
Gathering detailed insights and metrics for eslint-config-airbnb
Gathering detailed insights and metrics for eslint-config-airbnb
Gathering detailed insights and metrics for eslint-config-airbnb
@vue/eslint-config-airbnb-with-typescript
eslint-config-airbnb for Vue.js projects with TypeScript support
@terascope/eslint-config
A shared eslint config based on eslint-config-airbnb
eslint-config-weseek
Shareable configurations of ESLint by WESEEK, Inc. based on eslint-config-airbnb.
eslint-config-airbnb-base-hf
eslintconfig for hf base eslint-config-airbnb-base
npm install eslint-config-airbnb
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
145,506 Stars
1,982 Commits
26,537 Forks
3,757 Watching
5 Branches
520 Contributors
Updated on 27 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-4.7%
792,452
Compared to previous day
Last week
4.1%
4,222,888
Compared to previous week
Last month
15.3%
16,954,513
Compared to previous month
Last year
0.8%
185,211,745
Compared to previous year
3
5
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
1.1 Primitives: When you access a primitive type you work directly on its value.
string
number
boolean
null
undefined
symbol
bigint
1const foo = 1; 2let bar = foo; 3 4bar = 9; 5 6console.log(foo, bar); // => 1, 9
1.2 Complex: When you access a complex type you work on a reference to its value.
object
array
function
1const foo = [1, 2]; 2const bar = foo; 3 4bar[0] = 9; 5 6console.log(foo[0], bar[0]); // => 9, 9
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.
1// bad 2var a = 1; 3var b = 2; 4 5// good 6const a = 1; 7const 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 likevar
.
1// bad 2var count = 1; 3if (true) { 4 count += 1; 5} 6 7// good, use the let. 8let count = 1; 9if (true) { 10 count += 1; 11}
2.3 Note that both let
and const
are block-scoped, whereas var
is function-scoped.
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} 7console.log(a); // ReferenceError 8console.log(b); // ReferenceError 9console.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.
3.1 Use the literal syntax for object creation. eslint: no-new-object
1// bad 2const item = new Object(); 3 4// good 5const 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.
1 2function getKey(k) { 3 return `a key named ${k}`; 4} 5 6// bad 7const obj = { 8 id: 5, 9 name: 'San Francisco', 10}; 11obj[getKey('enabled')] = true; 12 13// good 14const obj = { 15 id: 5, 16 name: 'San Francisco', 17 [getKey('enabled')]: true, 18};
3.3 Use object method shorthand. eslint: object-shorthand
1// bad 2const atom = { 3 value: 1, 4 5 addValue: function (value) { 6 return atom.value + value; 7 }, 8}; 9 10// good 11const 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.
1const lukeSkywalker = 'Luke Skywalker'; 2 3// bad 4const obj = { 5 lukeSkywalker: lukeSkywalker, 6}; 7 8// good 9const 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.
1const anakinSkywalker = 'Anakin Skywalker'; 2const lukeSkywalker = 'Luke Skywalker'; 3 4// bad 5const obj = { 6 episodeOne: 1, 7 twoJediWalkIntoACantina: 2, 8 lukeSkywalker, 9 episodeThree: 3, 10 mayTheFourth: 4, 11 anakinSkywalker, 12}; 13 14// good 15const 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.
1// bad 2const bad = { 3 'foo': 3, 4 'bar': 4, 5 'data-blah': 5, 6}; 7 8// good 9const 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 https://npmjs.com/object.hasown,Object.hasOwn
can also be used as an alternative toObject.prototype.hasOwnProperty.call
.
1// bad 2console.log(object.hasOwnProperty(key)); 3 4// good 5console.log(Object.prototype.hasOwnProperty.call(object, key)); 6 7// better 8const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope. 9console.log(has.call(object, key)); 10 11// best 12console.log(Object.hasOwn(object, key)); // only supported in browsers that support ES2022 13 14/* or */ 15import has from 'has'; // https://www.npmjs.com/package/has 16console.log(has(object, key)); 17/* or */ 18console.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
1// very bad 2const original = { a: 1, b: 2 }; 3const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ 4delete copy.a; // so does this 5 6// bad 7const original = { a: 1, b: 2 }; 8const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 } 9 10// good 11const original = { a: 1, b: 2 }; 12const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 } 13 14const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
4.1 Use the literal syntax for array creation. eslint: no-array-constructor
1// bad 2const items = new Array(); 3 4// good 5const items = [];
4.2 Use Array#push instead of direct assignment to add items to an array.
1const someStack = []; 2 3// bad 4someStack[someStack.length] = 'abracadabra'; 5 6// good 7someStack.push('abracadabra');
4.3 Use array spreads ...
to copy arrays.
1// bad 2const len = items.length; 3const itemsCopy = []; 4let i; 5 6for (i = 0; i < len; i += 1) { 7 itemsCopy[i] = items[i]; 8} 9 10// good 11const itemsCopy = [...items];
4.4 To convert an iterable object to an array, use spreads ...
instead of Array.from
1const foo = document.querySelectorAll('.foo'); 2 3// good 4const nodes = Array.from(foo); 5 6// best 7const nodes = [...foo];
4.5 Use Array.from
for converting an array-like object to an array.
1const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 }; 2 3// bad 4const arr = Array.prototype.slice.call(arrLike); 5 6// good 7const arr = Array.from(arrLike);
4.6 Use Array.from
instead of spread ...
for mapping over iterables, because it avoids creating an intermediate array.
1// bad 2const baz = [...foo].map(bar); 3 4// good 5const 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
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 22inbox.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 32inbox.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
1// bad 2const arr = [ 3 [0, 1], [2, 3], [4, 5], 4]; 5 6const objectInArray = [{ 7 id: 1, 8}, { 9 id: 2, 10}]; 11 12const numberInArray = [ 13 1, 2, 14]; 15 16// good 17const arr = [[0, 1], [2, 3], [4, 5]]; 18 19const objectInArray = [ 20 { 21 id: 1, 22 }, 23 { 24 id: 2, 25 }, 26]; 27 28const numberInArray = [ 29 1, 30 2, 31];
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.
1// bad 2function getFullName(user) { 3 const firstName = user.firstName; 4 const lastName = user.lastName; 5 6 return `${firstName} ${lastName}`; 7} 8 9// good 10function getFullName(user) { 11 const { firstName, lastName } = user; 12 return `${firstName} ${lastName}`; 13} 14 15// best 16function getFullName({ firstName, lastName }) { 17 return `${firstName} ${lastName}`; 18}
5.2 Use array destructuring. eslint: prefer-destructuring
1const arr = [1, 2, 3, 4]; 2 3// bad 4const first = arr[0]; 5const second = arr[1]; 6 7// good 8const [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.
1// bad 2function 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 8const [left, __, top] = processInput(input); 9 10// good 11function processInput(input) { 12 // then a miracle occurs 13 return { left, right, top, bottom }; 14} 15 16// the caller selects only the data they need 17const { left, top } = processInput(input);
6.1 Use single quotes ''
for strings. eslint: quotes
1// bad 2const name = "Capt. Janeway"; 3 4// bad - template literals should contain interpolation or newlines 5const name = `Capt. Janeway`; 6 7// good 8const 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.
1// bad 2const errorMessage = 'This is a super long error that was thrown because \ 3of Batman. When you stop to think about how Batman had anything to do \ 4with this, you would get nowhere \ 5fast.'; 6 7// bad 8const 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 13const 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.
1// bad 2function sayHi(name) { 3 return 'How are you, ' + name + '?'; 4} 5 6// bad 7function sayHi(name) { 8 return ['How are you, ', name, '?'].join(); 9} 10 11// bad 12function sayHi(name) { 13 return `How are you, ${ name }?`; 14} 15 16// good 17function sayHi(name) { 18 return `How are you, ${name}?`; 19}
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.
1// bad 2const foo = '\'this\' \i\s \"quoted\"'; 3 4// good 5const foo = '\'this\' is "quoted"'; 6const foo = `my name is '${name}'`;
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)
1// bad 2function foo() { 3 // ... 4} 5 6// bad 7const foo = function () { 8 // ... 9}; 10 11// good 12// lexical name distinguished from the variable-referenced invocation(s) 13const 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.
1// immediately-invoked function expression (IIFE) 2(function () { 3 console.log('Welcome to the Internet. Please follow me.'); 4}());
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.
1// bad 2if (currentUser) { 3 function test() { 4 console.log('Nope.'); 5 } 6} 7 8// good 9let test; 10if (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.
1// bad 2function foo(name, options, arguments) { 3 // ... 4} 5 6// good 7function 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 likearguments
.
1// bad 2function concatenateAll() { 3 const args = Array.prototype.slice.call(arguments); 4 return args.join(''); 5} 6 7// good 8function concatenateAll(...args) { 9 return args.join(''); 10}
7.7 Use default parameter syntax rather than mutating function arguments.
1// really bad 2function 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 11function handleThings(opts) { 12 if (opts === void 0) { 13 opts = {}; 14 } 15 // ... 16} 17 18// good 19function handleThings(opts = {}) { 20 // ... 21}
7.8 Avoid side effects with default parameters.
Why? They are confusing to reason about.
1let b = 1; 2// bad 3function count(a = b++) { 4 console.log(a); 5} 6count(); // 1 7count(); // 2 8count(3); // 3 9count(); // 3
7.9 Always put default parameters last. eslint: default-param-last
1// bad 2function handleThings(opts = {}, name) { 3 // ... 4} 5 6// good 7function 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.
1// bad 2const add = new Function('a', 'b', 'return a + b'); 3 4// still bad 5const 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.
1// bad 2const f = function(){}; 3const g = function (){}; 4const h = function() {}; 5 6// good 7const x = function () {}; 8const 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.
1// bad 2function f1(obj) { 3 obj.key = 1; 4} 5 6// good 7function 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.
1// bad 2function f1(a) { 3 a = 1; 4 // ... 5} 6 7function f2(a) { 8 if (!a) { a = 1; } 9 // ... 10} 11 12// good 13function f3(a) { 14 const b = a || 1; 15 // ... 16} 17 18function 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
withapply
.
1// bad 2const x = [1, 2, 3, 4, 5]; 3console.log.apply(console, x); 4 5// good 6const x = [1, 2, 3, 4, 5]; 7console.log(...x); 8 9// bad 10new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5])); 11 12// good 13new 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
1// bad 2function foo(bar, 3 baz, 4 quux) { 5 // ... 6} 7 8// good 9function foo( 10 bar, 11 baz, 12 quux, 13) { 14 // ... 15} 16 17// bad 18console.log(foo, 19 bar, 20 baz); 21 22// good 23console.log( 24 foo, 25 bar, 26 baz, 27);
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.
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.
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 22function foo(callback) { 23 const val = callback(); 24 if (val === true) { 25 // Do something if callback returns true 26 } 27} 28 29let bool = false; 30 31// bad 32foo(() => bool = true); 33 34// good 35foo(() => { 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.
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.
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
1// bad 2const itemHeight = (item) => item.height <= 256 ? item.largeSize : item.smallSize; 3 4// bad 5const itemHeight = (item) => item.height >= 256 ? item.largeSize : item.smallSize; 6 7// good 8const itemHeight = (item) => (item.height <= 256 ? item.largeSize : item.smallSize); 9 10// good 11const 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
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)
9.1 Always use class
. Avoid manipulating prototype
directly.
Why?
class
syntax is more concise and easier to reason about.
1// bad 2function Queue(contents = []) { 3 this.queue = [...contents]; 4} 5Queue.prototype.pop = function () { 6 const value = this.queue[0]; 7 this.queue.splice(0, 1); 8 return value; 9}; 10 11// good 12class 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
.
1// bad 2const inherits = require('inherits'); 3function PeekableQueue(contents) { 4 Queue.apply(this, contents); 5} 6inherits(PeekableQueue, Queue); 7PeekableQueue.prototype.peek = function () { 8 return this.queue[0]; 9}; 10 11// good 12class PeekableQueue extends Queue { 13 peek() { 14 return this.queue[0]; 15 } 16}
9.3 Methods can return this
to help with method chaining.
1// bad 2Jedi.prototype.jump = function () { 3 this.jumping = true; 4 return true; 5}; 6 7Jedi.prototype.setHeight = function (height) { 8 this.height = height; 9}; 10 11const luke = new Jedi(); 12luke.jump(); // => true 13luke.setHeight(20); // => undefined 14 15// good 16class 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 28const luke = new Jedi(); 29 30luke.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.
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
1// bad 2class Jedi { 3 constructor() {} 4 5 getName() { 6 return this.name; 7 } 8} 9 10// bad 11class Rey extends Jedi { 12 constructor(...args) { 13 super(...args); 14 } 15} 16 17// good 18class 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.
1// bad 2class Foo { 3 bar() { return 1; } 4 bar() { return 2; } 5} 6 7// good 8class Foo { 9 bar() { return 1; } 10} 11 12// good 13class 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
1// bad 2class Foo { 3 bar() { 4 console.log('bar'); 5 } 6} 7 8// good - this is used 9class Foo { 10 bar() { 11 console.log(this.bar); 12 } 13} 14 15// good - constructor is exempt 16class Foo { 17 constructor() { 18 // ... 19 } 20} 21 22// good - static methods aren't expected to use this 23class Foo { 24 static bar() { 25 console.log('bar'); 26 } 27}
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.
1// bad 2const AirbnbStyleGuide = require('./AirbnbStyleGuide'); 3module.exports = AirbnbStyleGuide.es6; 4 5// ok 6import AirbnbStyleGuide from './AirbnbStyleGuide'; 7export default AirbnbStyleGuide.es6; 8 9// best 10import { es6 } from './AirbnbStyleGuide'; 11export default es6;
10.2 Do not use wildcard imports.
Why? This makes sure you have a single default export.
1// bad 2import * as AirbnbStyleGuide from './AirbnbStyleGuide'; 3 4// good 5import 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.
1// bad 2// filename es6.js 3export { es6 as default } from './AirbnbStyleGuide'; 4 5// good 6// filename es6.js 7import { es6 } from './AirbnbStyleGuide'; 8export 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.
1// bad 2import foo from 'foo'; 3// … some other imports … // 4import { named1, named2 } from 'foo'; 5 6// good 7import foo, { named1, named2 } from 'foo'; 8 9// good 10import 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.
1// bad 2let foo = 3; 3export { foo }; 4 5// good 6const foo = 3; 7export { 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.
1// bad 2export function foo() {} 3 4// good 5export default function foo() {}
10.7 Put all import
s above non-import statements.
eslint: import/first
Why? Since
import
s are hoisted, keeping them all at the top prevents surprising behavior.
1// bad 2import foo from 'foo'; 3foo.init(); 4 5import bar from 'bar'; 6 7// good 8import foo from 'foo'; 9import bar from 'bar'; 10 11foo.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.
1// bad 2import {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path'; 3 4// good 5import { 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
.
1// bad 2import fooSass from 'css!sass!foo.scss'; 3import barCss from 'style!css!bar.css'; 4 5// good 6import fooSass from 'foo.scss'; 7import 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.
1// bad 2import foo from './foo.js'; 3import bar from './bar.jsx'; 4import baz from './baz/index.jsx'; 5 6// good 7import foo from './foo'; 8import bar from './bar'; 9import baz from './baz';
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, andObject.keys()
/Object.values()
/Object.entries()
to produce arrays so you can iterate over objects.
1const numbers = [1, 2, 3, 4, 5]; 2 3// bad 4let sum = 0; 5for (let num of numbers) { 6 sum += num; 7} 8sum === 15; 9 10// good 11let sum = 0; 12numbers.forEach((num) => { 13 sum += num; 14}); 15sum === 15; 16 17// best (use the functional force) 18const sum = numbers.reduce((total, num) => total + num, 0); 19sum === 15; 20 21// bad 22const increasedByOne = []; 23for (let i = 0; i < numbers.length; i++) { 24 increasedByOne.push(numbers[i] + 1); 25} 26 27// good 28const increasedByOne = []; 29numbers.forEach((num) => { 30 increasedByOne.push(num + 1); 31}); 32 33// best (keeping it functional) 34const 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 forfunction
,function*
is a unique construct, different fromfunction
.
1// bad 2function * foo() { 3 // ... 4} 5 6// bad 7const bar = function * () { 8 // ... 9}; 10 11// bad 12const baz = function *() { 13 // ... 14}; 15 16// bad 17const quux = function*() { 18 // ... 19}; 20 21// bad 22function*foo() { 23 // ... 24} 25 26// bad 27function *foo() { 28 // ... 29} 30 31// very bad 32function 33* 34foo() { 35 // ... 36} 37 38// very bad 39const wat = function 40* 41() { 42 // ... 43}; 44 45// good 46function* foo() { 47 // ... 48} 49 50// good 51const foo = function* () { 52 // ... 53};
12.1 Use dot notation when accessing properties. eslint: dot-notation
1const luke = { 2 jedi: true, 3 age: 28, 4}; 5 6// bad 7const isJedi = luke['jedi']; 8 9// good 10const isJedi = luke.jedi;
12.2 Use bracket notation []
when accessing properties with a variable.
1const luke = { 2 jedi: true, 3 age: 28, 4}; 5 6function getProp(prop) { 7 return luke[prop]; 8} 9 10const isJedi = getProp('jedi');
12.3 Use exponentiation operator **
when calculating exponentiations. eslint: prefer-exponentiation-operator
.
1// bad 2const binary = Math.pow(2, 10); 3 4// good 5const binary = 2 ** 10;
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
1// bad 2superPower = new SuperPower(); 3 4// good 5const 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.
1// bad 2const items = getItems(), 3 goSportsTeam = true, 4 dragonball = 'z'; 5 6// bad 7// (compare to above, and try to spot the mistake) 8const items = getItems(), 9 goSportsTeam = true; 10 dragonball = 'z'; 11 12// good 13const items = getItems(); 14const goSportsTeam = true; 15const dragonball = 'z';
13.3 Group all your const
s and then group all your let
s.
Why? This is helpful when later on you might need to assign a variable depending on one of the previously assigned variables.
1// bad 2let i, len, dragonball, 3 items = getItems(), 4 goSportsTeam = true; 5 6// bad 7let i; 8const items = getItems(); 9let dragonball; 10const goSportsTeam = true; 11let len; 12 13// good 14const goSportsTeam = true; 15const items = getItems(); 16let dragonball; 17let i; 18let length;
13.4 Assign variables where you need them, but place them in a reasonable place.
Why?
let
andconst
are block scoped and not function scoped.
1// bad - unnecessary function call 2function 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 18function 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.
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 10console.log(a); // throws ReferenceError 11console.log(b); // 1 12console.log(c); // 1 13 14// good 15(function example() { 16 let a = 1; 17 let b = a; 18 let c = a; 19}()); 20 21console.log(a); // throws ReferenceError 22console.log(b); // throws ReferenceError 23console.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 ofnum++
ornum ++
. 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.
1// bad 2 3const array = [1, 2, 3]; 4let num = 1; 5num++; 6--num; 7 8let sum = 0; 9let truthyCount = 0; 10for (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 20const array = [1, 2, 3]; 21let num = 1; 22num += 1; 23num -= 1; 24 25const sum = array.reduce((a, b) => a + b, 0); 26const 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.
1// bad 2const foo = 3 superLongLongLongLongLongLongLongLongFunctionName(); 4 5// bad 6const foo 7 = 'superLongLongLongLongLongLongLongLongString'; 8 9// good 10const foo = ( 11 superLongLongLongLongLongLongLongLongFunctionName() 12); 13 14// good 15const 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.
1// bad 2 3const some_unused_var = 42; 4 5// Write-only variables are not considered as used. 6let y = 10; 7y = 5; 8 9// A read for a modification of itself is not considered as used. 10let z = 0; 11z = z + 1; 12 13// Unused function arguments. 14function getX(x, y) { 15 return x; 16} 17 18// good 19 20function getXPlusY(x, y) { 21 return x + y; 22} 23 24const x = 1; 25const y = a + 2; 26 27alert(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. 31const { type, ...coords } = data; 32// 'coords' is now the 'data' object without its 'type' property.
14.1 var
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.
1// we know this wouldn’t work (assuming there 2// is no notDefined global variable) 3function 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. 11function 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: 19function example() { 20 let declaredButNotAssigned; 21 console.log(declaredButNotAssigned); // => undefined 22 declaredButNotAssigned = true; 23} 24 25// using const and let 26function 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.
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.
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. 15function 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.
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.
1// bad 2 3// Variable a is being used before it is being defined. 4console.log(a); // this will be undefined, since while the declaration is hoisted, the initialization is not 5var a = 10; 6 7// Function fun is being called before being defined. 8fun(); 9function fun() {} 10 11// Class A is being used before being defined. 12new A(); // ReferenceError: Cannot access 'A' before initialization 13class 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 21console.log(a); // ReferenceError: Cannot access 'a' before initialization 22console.log(b); // ReferenceError: Cannot access 'b' before initialization 23let a = 10; 24const b = 5; 25 26 27// good 28 29var a = 10; 30console.log(a); // 10 31 32function fun() {} 33fun(); 34 35class A { 36} 37new A(); 38 39let a = 10; 40const b = 5; 41console.log(a); // 10 42console.log(b); // 5
For more information refer to JavaScript Scoping & Hoisting by Ben Cherry.
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:
''
, otherwise true1if ([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.
1// bad 2if (isValid === true) { 3 // ... 4} 5 6// good 7if (isValid) { 8 // ... 9} 10 11// bad 12if (name) { 13 // ... 14} 15 16// good 17if (name !== '') { 18 // ... 19} 20 21// bad 22if (collection.length) { 23 // ... 24} 25 26// good 27if (collection.length > 0) { 28 // ... 29}
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 itscase
is reached. This causes problems when multiplecase
clauses attempt to define the same thing.
1// bad 2switch (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 19switch (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
1// bad 2const foo = maybe1 > maybe2 3 ? "bar" 4 : value1 > value2 ? "baz" : null; 5 6// split into 2 separated ternary expressions 7const maybeNull = value1 > value2 ? 'baz' : null; 8 9// better 10const foo = maybe1 > maybe2 11 ? 'bar' 12 : maybeNull; 13 14// best 15const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
15.7 Avoid unneeded ternary statements. eslint: no-unneeded-ternary
1// bad 2const foo = a ? a : b; 3const bar = c ? true : false; 4const baz = c ? false : true; 5const quux = a != null ? a : b; 6 7// good 8const foo = a || b; 9const bar = !!c; 10const baz = !c; 11const 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.
1// bad 2const foo = a && b < 0 || c > 0 || d + 1 === 0; 3 4// bad 5const bar = a ** b - 5 % d; 6 7// bad 8// one may be confused into thinking (a || b) && c 9if (a || b && c) { 10 return d; 11} 12 13// bad 14const bar = a + b / c * d; 15 16// good 17const foo = (a && b < 0) || c > 0 || (d + 1 === 0); 18 19// good 20const bar = a ** b - (5 % d); 21 22// good 23if (a || (b && c)) { 24 return d; 25} 26 27// good 28const 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.
1// bad 2const value = 0 ?? 'default'; 3// returns 0, not 'default' 4 5// bad 6const value = '' ?? 'default'; 7// returns '', not 'default' 8 9// good 10const value = null ?? 'default'; 11// returns 'default' 12 13// good 14const user = { 15 name: 'John', 16 age: null 17}; 18const age = user.age ?? 18; 19// returns 18
16.1 Use braces with all multiline blocks. eslint: nonblock-statement-body-position
1// bad 2if (test) 3 return false; 4 5// good 6if (test) return false; 7 8// good 9if (test) { 10 return false; 11} 12 13// bad 14function foo() { return false; } 15 16// good 17function 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
1// bad 2if (test) { 3 thing1(); 4 thing2(); 5} 6else { 7 thing3(); 8} 9 10// good 11if (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
1// bad 2function foo() { 3 if (x) { 4 return x; 5 } else { 6 return y; 7 } 8} 9 10// bad 11function cats() { 12 if (x) { 13 return x; 14 } else if (y) { 15 return y; 16 } 17} 18 19// bad 20function dogs() { 21 if (x) { 22 return x; 23 } else { 24 if (y) { 25 return y; 26 } 27 } 28} 29 30// good 31function foo() { 32 if (x) { 33 return x; 34 } 35 36 return y; 37} 38 39// good 40function cats() { 41 if (x) { 42 return x; 43 } 44 45 if (y) { 46 return y; 47 } 48} 49 50// good 51function dogs(x) { 52 if (x) { 53 if (z) { 54 return y; 55 } 56 } else { 57 return z; 58 } 59}
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.
1// bad 2if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) { 3 thing1(); 4} 5 6// bad 7if (foo === 123 && 8 bar === 'abc') { 9 thing1(); 10} 11 12// bad 13if (foo === 123 14 && bar === 'abc') { 15 thing1(); 16} 17 18// bad 19if ( 20 foo === 123 && 21 bar === 'abc' 22) { 23 thing1(); 24} 25 26// good 27if ( 28 foo === 123 29 && bar === 'abc' 30) { 31 thing1(); 32} 33 34// good 35if ( 36 (foo === 123 || bar === 'abc') 37 && doesItLookGoodWhenItBecomesThatLong() 38 && isThisReallyHappening() 39) { 40 thing1(); 41} 42 43// good 44if (foo === 123 && bar === 'abc') { 45 thing1(); 46}
17.2 Don't use selection operators in place of control statements.
1// bad 2!isRunning && startRunning(); 3 4// good 5if (!isRunning) { 6 startRunning(); 7}
18.1 Use /** ... */
for multiline comments.
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 7function 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 */ 19function 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.
1// bad 2const active = true; // is current tab 3 4// good 5// is current tab 6const active = true; 7 8// bad 9function 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 18function 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 28function 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
1// bad 2//is current tab 3const active = true; 4 5// good 6// is current tab 7const active = true; 8 9// bad 10/** 11 *make() returns a new element 12 *based on the passed-in tag name 13 */ 14function 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 */ 26function make(tag) { 27 28 // ... 29 30 return element; 31}
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.
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.
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}
19.1 Use soft tabs (space character) set to 2 spaces. eslint: indent
1// bad 2function foo() { 3∙∙∙∙let name; 4} 5 6// bad 7function bar() { 8∙let name; 9} 10 11// good 12function baz() { 13∙∙let name; 14}
19.2 Place 1 space before the leading brace. eslint: space-before-blocks
1// bad 2function test(){ 3 console.log('test'); 4} 5 6// good 7function test() { 8 console.log('test'); 9} 10 11// bad 12dog.set('attr',{ 13 age: '1 year', 14 breed: 'Bernese Mountain Dog', 15}); 16 17// good 18dog.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
1// bad 2if(isJedi) { 3 fight (); 4} 5 6// good 7if (isJedi) { 8 fight(); 9} 10 11// bad 12function fight () { 13 console.log ('Swooosh!'); 14} 15 16// good 17function fight() { 18 console.log('Swooosh!'); 19}
19.4 Set off operators with spaces. eslint: space-infix-ops
1// bad 2const x=y+5; 3 4// good 5const x = y + 5;
19.5 End files with a single newline character. eslint: eol-last
1// bad 2import { es6 } from './AirbnbStyleGuide'; 3 // ... 4export default es6;
1// bad 2import { es6 } from './AirbnbStyleGuide'; 3 // ... 4export default es6;↵ 5↵
1// good 2import { es6 } from './AirbnbStyleGuide'; 3 // ... 4export 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
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 21const 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 27const 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 37const leds = stage.selectAll('.led').data(data); 38const svg = leds.enter().append('svg:svg'); 39svg.classed('led', true).attr('width', (radius + margin) * 2); 40const g = svg.append('svg:g'); 41g.attr('transform', `translate(${radius + margin}, ${radius + margin})`).call(tron.led);
19.7 Leave a blank line after blocks and before the next statement.
1// bad 2if (foo) { 3 return bar; 4} 5return baz; 6 7// good 8if (foo) { 9 return bar; 10} 11 12return baz; 13 14// bad 15const obj = { 16 foo() { 17 }, 18 bar() { 19 }, 20}; 21return obj; 22 23// good 24const obj = { 25 foo() { 26 }, 27 28 bar() { 29 }, 30}; 31 32return obj; 33 34// bad 35const arr = [ 36 function foo() { 37 }, 38 function bar() { 39 }, 40]; 41return arr; 42 43// good 44const arr = [ 45 function foo() { 46 }, 47 48 function bar() { 49 }, 50]; 51 52return arr;
19.8 Do not pad your blocks with blank lines. eslint: padded-blocks
1// bad 2function bar() { 3 4 console.log(foo); 5 6} 7 8// bad 9if (baz) { 10 11 console.log(quux); 12} else { 13 console.log(foo); 14 15} 16 17// bad 18class Foo { 19 20 constructor(bar) { 21 this.bar = bar; 22 } 23} 24 25// good 26function bar() { 27 console.log(foo); 28} 29 30// good 31if (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
1// bad 2class 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 31class 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
1// bad 2function bar( foo ) { 3 return foo; 4} 5 6// good 7function bar(foo) { 8 return foo; 9} 10 11// bad 12if ( foo ) { 13 console.log(foo); 14} 15 16// good 17if (foo) { 18 console.log(foo); 19}
19.11 Do not add spaces inside brackets. eslint: array-bracket-spacing
1// bad 2const foo = [ 1, 2, 3 ]; 3console.log(foo[ 0 ]); 4 5// good 6const foo = [1, 2, 3]; 7console.log(foo[0]);
19.12 Add spaces inside curly braces. eslint: object-curly-spacing
1// bad 2const foo = {clark: 'kent'}; 3 4// good 5const 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.
1// bad 2const 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 8const 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 16const 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
1// bad 2function foo() {return true;} 3if (foo) { bar = 0;} 4 5// good 6function foo() { return true; } 7if (foo) { bar = 0; }
19.15 Avoid spaces before commas and require a space after commas. eslint: comma-spacing
1// bad 2const foo = 1,bar = 2; 3const arr = [1 , 2]; 4 5// good 6const foo = 1, bar = 2; 7const arr = [1, 2];
19.16 Enforce spacing inside of computed property brackets. eslint: computed-property-spacing
1// bad 2obj[foo ] 3obj[ 'foo'] 4const x = {[ b ]: a} 5obj[foo[ bar ]] 6 7// good 8obj[foo] 9obj['foo'] 10const x = { [b]: a } 11obj[foo[bar]]
19.17 Avoid spaces between functions and their invocations. eslint: func-call-spacing
1// bad 2func (); 3 4func 5(); 6 7// good 8func();
19.18 Enforce spacing between keys and values in object literal properties. eslint: key-spacing
1// bad 2const obj = { foo : 42 }; 3const obj2 = { foo:42 }; 4 5// good 6const obj = { foo: 42 };
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
1// bad - multiple empty lines 2const x = 1; 3 4 5const y = 2; 6 7// bad - 2+ newlines at end of file 8const x = 1; 9const y = 2; 10 11 12// bad - 1+ newline(s) at beginning of file 13 14const x = 1; 15const y = 2; 16 17// good 18const x = 1; 19const y = 2; 20
20.1 Leading commas: Nope. eslint: comma-style
1// bad 2const story = [ 3 once 4 , upon 5 , aTime 6]; 7 8// good 9const story = [ 10 once, 11 upon, 12 aTime, 13]; 14 15// bad 16const hero = { 17 firstName: 'Ada' 18 , lastName: 'Lovelace' 19 , birthYear: 1815 20 , superPower: 'computers' 21}; 22 23// good 24const 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.
1// bad - git diff without trailing comma 2const 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 10const hero = { 11 firstName: 'Florence', 12 lastName: 'Nightingale', 13+ inventorOf: ['coxcomb chart', 'modern nursing'], 14};
1// bad 2const hero = { 3 firstName: 'Dana', 4 lastName: 'Scully' 5}; 6 7const heroes = [ 8 'Batman', 9 'Superman' 10]; 11 12// good 13const hero = { 14 firstName: 'Dana', 15 lastName: 'Scully', 16}; 17 18const heroes = [ 19 'Batman', 20 'Superman', 21]; 22 23// bad 24function createHero( 25 firstName, 26 lastName, 27 inventorOf 28) { 29 // does nothing 30} 31 32// good 33function 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) 42function createHero( 43 firstName, 44 lastName, 45 inventorOf, 46 ...heroArgs 47) { 48 // does nothing 49} 50 51// bad 52createHero( 53 firstName, 54 lastName, 55 inventorOf 56); 57 58// good 59createHero( 60 firstName, 61 lastName, 62 inventorOf, 63); 64 65// good (note that a comma must not appear after a "rest" element) 66createHero( 67 firstName, 68 lastName, 69 inventorOf, 70 ...heroArgs 71);
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.
1// bad - raises exception 2const luke = {} 3const leia = {} 4[luke, leia].forEach((jedi) => jedi.father = 'vader') 5 6// bad - raises exception 7const 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! 14function foo() { 15 return 16 'search your feelings, you know it to be foo' 17} 18 19// good 20const luke = {}; 21const leia = {}; 22[luke, leia].forEach((jedi) => { 23 jedi.father = 'vader'; 24}); 25 26// good 27const reaction = 'No! That’s impossible!'; 28(async function meanwhileOnTheFalcon() { 29 // handle `leia`, `lando`, `chewie`, `r2`, `c3p0` 30 // ... 31}()); 32 33// good 34function foo() { 35 return 'search your feelings, you know it to be foo'; 36}
22.2 Strings: eslint: no-new-wrappers
1// => this.reviewScore = 9; 2 3// bad 4const totalScore = new String(this.reviewScore); // typeof totalScore is "object" not "string" 5 6// bad 7const totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf() 8 9// bad 10const totalScore = this.reviewScore.toString(); // isn’t guaranteed to return a string 11 12// good 13const 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 isundefined
or0
, it is assumed to be10
except when the number begins with the character pairs0x
or0X
, 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.
1const inputValue = '4'; 2 3// bad 4const val = new Number(inputValue); 5 6// bad 7const val = +inputValue; 8 9// bad 10const val = inputValue >> 0; 11 12// bad 13const val = parseInt(inputValue); 14 15// good 16const val = Number(inputValue); 17 18// good 19const 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.
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 */ 7const 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:
12147483647 >> 0; // => 2147483647 22147483648 >> 0; // => -2147483648 32147483649 >> 0; // => -2147483647
22.6 Booleans: eslint: no-new-wrappers
1const age = 0; 2 3// bad 4const hasAge = new Boolean(age); 5 6// good 7const hasAge = Boolean(age); 8 9// best 10const hasAge = !!age;
23.1 Avoid single letter names. Be descriptive with your naming. eslint: id-length
1// bad 2function q() { 3 // ... 4} 5 6// good 7function query() { 8 // ... 9}
23.2 Use camelCase when naming objects, functions, and instances. eslint: camelcase
1// bad 2const OBJEcttsssss = {}; 3const this_is_my_object = {}; 4function c() {} 5 6// good 7const thisIsMyObject = {}; 8function thisIsMyFunction() {}
23.3 Use PascalCase only when naming constructors or classes. eslint: new-cap
1// bad 2function user(options) { 3 this.name = options.name; 4} 5 6const bad = new user({ 7 name: 'nope', 8}); 9 10// good 11class User { 12 constructor(options) { 13 this.name = options.name; 14 } 15} 16 17const 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.
1// bad 2this.__firstName__ = 'Panda'; 3this.firstName_ = 'Panda'; 4this._firstName = 'Panda'; 5 6// good 7this.firstName = 'Panda'; 8 9// good, in environments where WeakMaps are available 10// see https://compat-table.github.io/compat-table/es6/#test-WeakMap 11const firstNames = new WeakMap(); 12firstNames.set(this, 'Panda');
23.5 Don’t save references to this
. Use arrow functions or Function#bind.
1// bad 2function foo() { 3 const self = this; 4 return function () { 5 console.log(self); 6 }; 7} 8 9// bad 10function foo() { 11 const that = this; 12 return function () { 13 console.log(that); 14 }; 15} 16 17// good 18function foo() { 19 return () => { 20 console.log(this); 21 }; 22}
23.6 A base filename should exactly match the name of its default export.
1// file 1 contents 2class CheckBox { 3 // ... 4} 5export default CheckBox; 6 7// file 2 contents 8export default function fortyTwo() { return 42; } 9 10// file 3 contents 11export default function insideDirectory() {} 12 13// in some other file 14// bad 15import CheckBox from './checkBox'; // PascalCase import/export, camelCase filename 16import FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase export 17import InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export 18 19// bad 20import CheckBox from './check_box'; // PascalCase import/export, snake_case filename 21import forty_two from './forty_two'; // snake_case import/filename, camelCase export 22import inside_directory from './inside_directory'; // snake_case import, camelCase export 23import index from './inside_directory/index'; // requiring the index file explicitly 24import insideDirectory from './insideDirectory/index'; // requiring the index file explicitly 25 26// good 27import CheckBox from './CheckBox'; // PascalCase export/import/filename 28import fortyTwo from './fortyTwo'; // camelCase export/import/filename 29import 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.
1function makeStyleGuide() { 2 // ... 3} 4 5export default makeStyleGuide;
23.8 Use PascalCase when you export a constructor / class / singleton / function library / bare object.
1const AirbnbStyleGuide = { 2 es6: { 3 }, 4}; 5 6export 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.
1// bad 2import SmsContainer from './containers/SmsContainer'; 3 4// bad 5const HttpRequests = [ 6 // ... 7]; 8 9// good 10import SMSContainer from './containers/SMSContainer'; 11 12// good 13const HTTPRequests = [ 14 // ... 15]; 16 17// also good 18const httpRequests = [ 19 // ... 20]; 21 22// best 23import TextMessageContainer from './containers/TextMessageContainer'; 24 25// best 26const 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.
const
variables? - This is unnecessary, so uppercasing should not be used for constants within a file. It should be used for exported constants however.EXPORTED_OBJECT.key
) and maintain that all nested properties do not change.1// bad 2const PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file'; 3 4// bad 5export const THING_TO_BE_CHANGED = 'should obviously not be uppercased'; 6 7// bad 8export let REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables'; 9 10// --- 11 12// allowed but does not supply semantic value 13export const apiKey = 'SOMEKEY'; 14 15// better in most cases 16export const API_KEY = 'SOMEKEY'; 17 18// --- 19 20// bad - unnecessarily uppercases key while adding no semantic value 21export const MAPPING = { 22 KEY: 'value' 23}; 24 25// good 26export const MAPPING = { 27 key: 'value', 28};
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')
.
1// bad 2class Dragon { 3 get age() { 4 // ... 5 } 6 7 set age(value) { 8 // ... 9 } 10} 11 12// good 13class 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()
.
1// bad 2if (!dragon.age()) { 3 return false; 4} 5 6// good 7if (!dragon.hasAge()) { 8 return false; 9}
24.4 It’s okay to create get()
and set()
functions, but be consistent.
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}
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:
1// bad 2$(this).trigger('listingUpdated', listing.id); 3 4// ... 5 6$(this).on('listingUpdated', (e, listingID) => { 7 // do something with listingID 8});
prefer:
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});
26.1 Prefix jQuery object variables with a $
.
1// bad 2const sidebar = $('.sidebar'); 3 4// good 5const $sidebar = $('.sidebar'); 6 7// good 8const $sidebarBtn = $('.sidebar-btn');
26.2 Cache jQuery lookups.
1// bad 2function setSidebar() { 3 $('.sidebar').hide(); 4 5 // ... 6 7 $('.sidebar').css({ 8 'background-color': 'pink', 9 }); 10} 11 12// good 13function setSidebar() { 14 const $sidebar = $('.sidebar'); 15 $sidebar.hide(); 16 17 // ... 18 19 $sidebar.css({ 20 'background-color': 'pink', 21 }); 22}
26.4 Use find
with scoped jQuery object queries.
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();
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.
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.
1// bad 2isNaN('1.2'); // false 3isNaN('1.2.3'); // true 4 5// good 6Number.isNaN('1.2.3'); // false 7Number.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.
1// bad 2isFinite('2e3'); // true 3 4// good 5Number.isFinite('2e3'); // false 6Number.isFinite(parseInt('2e3', 10)); // true
30.1 Yup.
1function foo() { 2 return true; 3}
mocha
and jest
at Airbnb. tape
is also used occasionally for small, separate modules.map()
, reduce()
, and filter()
optimized for traversing arrays?Learning ES6+
Read This
Tools
Other Style Guides
Other Styles
Further Reading
Books
Blogs
Podcasts
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.
This style guide is also available in other languages:
(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.
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.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
5 commit(s) and 6 issue activity found in the last 90 days -- score normalized to 9
Reason
Found 16/17 approved changesets -- score normalized to 9
Reason
security policy file detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More