# Airbnb JavaScript Style Guide() {

_A mostly reasonable approach to JavaScript_

\> **Note**: this guide assumes you are using [Babel](https://babeljs.io/), and requires that you use [babel-preset-airbnb](https://npmjs.com/babel-preset-airbnb) or the equivalent. It also assumes you are installing shims/polyfills in your app, with [airbnb-browser-shims](https://npmjs.com/airbnb-browser-shims) or the equivalent.

This guide is available in other languages too. See [Translation](/content/airbnb/javascript#translation/index.html)

Other Style Guides

[ES5 (Deprecated)](https://github.com/airbnb/javascript/tree/es5-deprecated/es5)

[React](/content/airbnb/react/index.html)

[CSS-in-JavaScript](/content/airbnb/css-in-javascript/index.html)

[CSS & Sass](https://github.com/airbnb/css)

[Ruby](https://github.com/airbnb/ruby)

## Table of Contents

1.

[Types](/content/airbnb/javascript#types/index.html)

1.

[References](/content/airbnb/javascript#references/index.html)

1.

[Objects](/content/airbnb/javascript#objects/index.html)

1.

[Arrays](/content/airbnb/javascript#arrays/index.html)

1.

[Destructuring](/content/airbnb/javascript#destructuring/index.html)

1.

[Strings](/content/airbnb/javascript#strings/index.html)

1.

[Functions](/content/airbnb/javascript#functions/index.html)

1.

[Arrow Functions](/content/airbnb/javascript#arrow-functions/index.html)

1.

[Classes & Constructors](/content/airbnb/javascript#classes--constructors/index.html)

1.

[Modules](/content/airbnb/javascript#modules/index.html)

1.

[Iterators and Generators](/content/airbnb/javascript#iterators-and-generators/index.html)

1.

[Properties](/content/airbnb/javascript#properties/index.html)

1.

[Variables](/content/airbnb/javascript#variables/index.html)

1.

[Hoisting](/content/airbnb/javascript#hoisting/index.html)

1.

[Comparison Operators & Equality](/content/airbnb/javascript#comparison-operators--equality/index.html)

1.

[Blocks](/content/airbnb/javascript#blocks/index.html)

1.

[Control Statements](/content/airbnb/javascript#control-statements/index.html)

1.

[Comments](/content/airbnb/javascript#comments/index.html)

1.

[Whitespace](/content/airbnb/javascript#whitespace/index.html)

1.

[Commas](/content/airbnb/javascript#commas/index.html)

1.

[Semicolons](/content/airbnb/javascript#semicolons/index.html)

1.

[Type Casting & Coercion](/content/airbnb/javascript#type-casting--coercion/index.html)

1.

[Naming Conventions](/content/airbnb/javascript#naming-conventions/index.html)

1.

[Accessors](/content/airbnb/javascript#accessors/index.html)

1.

[Events](/content/airbnb/javascript#events/index.html)

1.

[jQuery](/content/airbnb/javascript#jquery/index.html)

1.

[ECMAScript 5 Compatibility](/content/airbnb/javascript#ecmascript-5-compatibility/index.html)

1.

[ECMAScript 6+ (ES 2015+) Styles](/content/airbnb/javascript#ecmascript-6-es-2015-styles/index.html)

1.

[Standard Library](/content/airbnb/javascript#standard-library/index.html)

1.

[Testing](/content/airbnb/javascript#testing/index.html)

1.

[Performance](/content/airbnb/javascript#performance/index.html)

1.

[Resources](/content/airbnb/javascript#resources/index.html)

1.

[In the Wild](/content/airbnb/javascript#in-the-wild/index.html)

1.

[Translation](/content/airbnb/javascript#translation/index.html)

1.

[The JavaScript Style Guide Guide](/content/airbnb/javascript#the-javascript-style-guide-guide/index.html)

1.

[Chat With Us About JavaScript](/content/airbnb/javascript#chat-with-us-about-javascript/index.html)

1.

[Contributors](/content/airbnb/javascript#contributors/index.html)

1.

[License](/content/airbnb/javascript#license/index.html)

1.

[Amendments](/content/airbnb/javascript#amendments/index.html)

## Types

[1.1](/content/airbnb/javascript#types--primitives/index.html) **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](/content/airbnb/javascript#types--complex/index.html) **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`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## References

[2.1](/content/airbnb/javascript#references--prefer-const/index.html) Use `const` for all of your references; avoid using `var`. eslint: [`prefer-const`](https://eslint.org/docs/rules/prefer-const), [`no-const-assign`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#references--disallow-var/index.html) If you must reassign references, use `let` instead of `var`. eslint: [`no-var`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#references--block-scope/index.html) 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.

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Objects

[3.1](/content/airbnb/javascript#objects--no-new/index.html) Use the literal syntax for object creation. eslint: [`no-new-object`](https://eslint.org/docs/rules/no-new-object)

javascript

`1// bad
2    const item = new Object();
3
4    // good
5    const item = {};`

[3.2](/content/airbnb/javascript#es6-computed-properties/index.html) 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](/content/airbnb/javascript#es6-object-shorthand/index.html) Use object method shorthand. eslint: [`object-shorthand`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#es6-object-concise/index.html) Use property value shorthand. eslint: [`object-shorthand`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#objects--grouped-shorthand/index.html) 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](/content/airbnb/javascript#objects--quoted-props/index.html) Only quote properties that are invalid identifiers. eslint: [`quote-props`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#objects--prototype-builtins/index.html) Do not call `Object.prototype` methods directly, such as `hasOwnProperty`, `propertyIsEnumerable`, and `isPrototypeOf`. eslint: [`no-prototype-builtins`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#objects--rest-spread/index.html) Prefer the object spread syntax over [`Object.assign`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/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`](https://eslint.org/docs/rules/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 }``

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Arrays

[4.1](/content/airbnb/javascript#arrays--literals/index.html) Use the literal syntax for array creation. eslint: [`no-array-constructor`](https://eslint.org/docs/rules/no-array-constructor)

javascript

`1// bad
2    const items = new Array();
3
4    // good
5    const items = [];`

[4.2](/content/airbnb/javascript#arrays--push/index.html) Use [Array#push](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/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](/content/airbnb/javascript#es6-array-spreads/index.html) 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](/content/airbnb/javascript#arrays--from-iterable/index.html) To convert an iterable object to an array, use spreads `...` instead of [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/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](/content/airbnb/javascript#arrays--from-array-like/index.html) Use [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/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](/content/airbnb/javascript#arrays--mapping/index.html) Use [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/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](/content/airbnb/javascript#arrays--callback-return/index.html) 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](/content/airbnb/javascript#arrows--implicit-return/index.html). eslint: [`array-callback-return`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#arrays--bracket-newline/index.html) 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    ];`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Destructuring

[5.1](/content/airbnb/javascript#destructuring--object/index.html) Use object destructuring when accessing and using multiple properties of an object. eslint: [`prefer-destructuring`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#destructuring--array/index.html) Use array destructuring. eslint: [`prefer-destructuring`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#destructuring--object-over-array/index.html) 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);`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Strings

[6.1](/content/airbnb/javascript#strings--quotes/index.html) Use single quotes `''` for strings. eslint: [`quotes`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#strings--line-length/index.html) 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](/content/airbnb/javascript#es6-template-literals/index.html) When programmatically building up strings, use template strings instead of concatenation. eslint: [`prefer-template`](https://eslint.org/docs/rules/prefer-template) [`template-curly-spacing`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#strings--eval/index.html) Never use `eval()` on a string; it opens too many vulnerabilities. eslint: [`no-eval`](https://eslint.org/docs/rules/no-eval)

[6.5](/content/airbnb/javascript#strings--escaping/index.html) Do not unnecessarily escape characters in strings. eslint: [`no-useless-escape`](https://eslint.org/docs/rules/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}'`;``

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Functions

[7.1](/content/airbnb/javascript#functions--declarations/index.html) Use named function expressions instead of function declarations. eslint: [`func-style`](https://eslint.org/docs/rules/func-style), [`func-names`](https://eslint.org/docs/latest/rules/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](https://github.com/airbnb/javascript/issues/794))

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](/content/airbnb/javascript#functions--iife/index.html) Wrap immediately invoked function expressions in parentheses. eslint: [`wrap-iife`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#functions--in-blocks/index.html) 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`](https://eslint.org/docs/rules/no-loop-func)

[7.4](/content/airbnb/javascript#functions--note-on-blocks/index.html) **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](/content/airbnb/javascript#functions--arguments-shadow/index.html) 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](/content/airbnb/javascript#es6-rest/index.html) Never use `arguments`, opt to use rest syntax `...` instead. eslint: [`prefer-rest-params`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#es6-default-parameters/index.html) 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](/content/airbnb/javascript#functions--default-side-effects/index.html) 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](/content/airbnb/javascript#functions--defaults-last/index.html) Always put default parameters last. eslint: [`default-param-last`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#functions--constructor/index.html) Never use the Function constructor to create a new function. eslint: [`no-new-func`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#functions--signature-spacing/index.html) Spacing in a function signature. eslint: [`space-before-function-paren`](https://eslint.org/docs/rules/space-before-function-paren) [`space-before-blocks`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#functions--mutate-params/index.html) Never mutate parameters. eslint: [`no-param-reassign`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#functions--reassign-params/index.html) Never reassign parameters. eslint: [`no-param-reassign`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#functions--spread-vs-apply/index.html) Prefer the use of the spread syntax `...` to call variadic functions. eslint: [`prefer-spread`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#functions--signature-invocation-indentation/index.html) 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`](https://eslint.org/docs/rules/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    );`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Arrow Functions

[8.1](/content/airbnb/javascript#arrows--use-them/index.html) When you must use an anonymous function (as when passing an inline callback), use arrow function notation. eslint: [`prefer-arrow-callback`](https://eslint.org/docs/rules/prefer-arrow-callback), [`arrow-spacing`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#arrows--implicit-return/index.html) If the function body consists of a single statement returning an [expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions) without side effects, omit the braces and use the implicit return. Otherwise, keep the braces and use a `return` statement. eslint: [`arrow-parens`](https://eslint.org/docs/rules/arrow-parens), [`arrow-body-style`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#arrows--paren-wrap/index.html) 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](/content/airbnb/javascript#arrows--one-arg-parens/index.html) Always include parentheses around arguments for clarity and consistency. eslint: [`arrow-parens`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#arrows--confusing/index.html) Avoid confusing arrow function syntax (`=>`) with comparison operators (`<=`, `>=`). eslint: [`no-confusing-arrow`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--implicit-arrow-linebreak/index.html) Enforce the location of arrow function bodies with implicit returns. eslint: [`implicit-arrow-linebreak`](https://eslint.org/docs/rules/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    )`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Classes & Constructors

[9.1](/content/airbnb/javascript#constructors--use-class/index.html) 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](/content/airbnb/javascript#constructors--extends/index.html) 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](/content/airbnb/javascript#constructors--chaining/index.html) 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](/content/airbnb/javascript#constructors--tostring/index.html) 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](/content/airbnb/javascript#constructors--no-useless/index.html) 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`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#classes--no-duplicate-members/index.html) Avoid duplicate class members. eslint: [`no-dupe-class-members`](https://eslint.org/docs/rules/no-dupe-class-members)

\> Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug.

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](/content/airbnb/javascript#classes--methods-use-this/index.html) 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`](https://eslint.org/docs/rules/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    }`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Modules

[10.1](/content/airbnb/javascript#modules--use-them/index.html) 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](/content/airbnb/javascript#modules--no-wildcard/index.html) 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](/content/airbnb/javascript#modules--no-export-from-import/index.html) 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](/content/airbnb/javascript#modules--no-duplicate-imports/index.html) Only import from a path in one place.

eslint: [`no-duplicate-imports`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#modules--no-mutable-exports/index.html) Do not export mutable bindings.

eslint: [`import/no-mutable-exports`](https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md)

\> 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](/content/airbnb/javascript#modules--prefer-default-export/index.html) In modules with a single export, prefer default export over named export.

eslint: [`import/prefer-default-export`](https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md)

\> 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](/content/airbnb/javascript#modules--imports-first/index.html) Put all `import`s above non-import statements.

eslint: [`import/first`](https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/first.md)

\> Why? Since `import`s 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](/content/airbnb/javascript#modules--multiline-imports-over-newlines/index.html) Multiline imports should be indented just like multiline array and object literals.

eslint: [`object-curly-newline`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#modules--no-webpack-loader-syntax/index.html) Disallow Webpack loader syntax in module import statements.

eslint: [`import/no-webpack-loader-syntax`](https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/no-webpack-loader-syntax.md)

\> 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](/content/airbnb/javascript#modules--import-extensions/index.html) Do not include JavaScript filename extensions

eslint: [`import/extensions`](https://github.com/import-js/eslint-plugin-import/blob/master/docs/rules/extensions.md)

\> 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';`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Iterators and Generators

[11.1](/content/airbnb/javascript#iterators--nope/index.html) Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like `for-in` or `for-of`. eslint: [`no-iterator`](https://eslint.org/docs/rules/no-iterator) [`no-restricted-syntax`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#generators--nope/index.html) Don’t use generators for now.

\> Why? They don’t transpile well to ES5.

[11.3](/content/airbnb/javascript#generators--spacing/index.html) If you must use generators, or if you disregard [our advice](/content/airbnb/javascript#generators--nope/index.html), make sure their function signature is spaced properly. eslint: [`generator-star-spacing`](https://eslint.org/docs/rules/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    };`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Properties

[12.1](/content/airbnb/javascript#properties--dot/index.html) Use dot notation when accessing properties. eslint: [`dot-notation`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#properties--bracket/index.html) 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](/content/airbnb/javascript#es2016-properties--exponentiation-operator/index.html) Use exponentiation operator `**` when calculating exponentiations. eslint: [`prefer-exponentiation-operator`](https://eslint.org/docs/rules/prefer-exponentiation-operator).

javascript

`1// bad
2    const binary = Math.pow(2, 10);
3
4    // good
5    const binary = 2 ** 10;`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Variables

[13.1](/content/airbnb/javascript#variables--const/index.html) 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`](https://eslint.org/docs/rules/no-undef) [`prefer-const`](https://eslint.org/docs/rules/prefer-const)

javascript

`1// bad
2    superPower = new SuperPower();
3
4    // good
5    const superPower = new SuperPower();`

[13.2](/content/airbnb/javascript#variables--one-const/index.html) Use one `const` or `let` declaration per variable or assignment. eslint: [`one-var`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#variables--const-let-group/index.html) 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.

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](/content/airbnb/javascript#variables--define-where-used/index.html) 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](/content/airbnb/javascript#variables--no-chain-assignment/index.html) Don’t chain variable assignments. eslint: [`no-multi-assign`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#variables--unary-increment-decrement/index.html) Avoid using unary increments and decrements (`++`, `--`). eslint [`no-plusplus`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#variables--linebreak/index.html) Avoid linebreaks before or after `=` in an assignment. If your assignment violates [`max-len`](https://eslint.org/docs/rules/max-len), surround the value in parens. eslint [`operator-linebreak`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#variables--no-unused-vars/index.html) Disallow unused variables. eslint: [`no-unused-vars`](https://eslint.org/docs/rules/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.`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Hoisting

[14.1](/content/airbnb/javascript#hoisting--about/index.html)`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)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz). It’s important to know why [typeof is no longer safe](https://web.archive.org/web/20200121061528/http://es-discourse.com/t/why-typeof-is-no-longer-safe/15).

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](/content/airbnb/javascript#hoisting--anon-expressions/index.html) 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](/content/airbnb/javascript#hoisting--named-expressions/index.html) 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](/content/airbnb/javascript#hoisting--declarations/index.html) 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](/content/airbnb/javascript#no-use-before-define/index.html) Variables, classes, and functions should be defined before they can be used. eslint: [`no-use-before-define`](https://eslint.org/docs/latest/rules/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](https://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting/) by [Ben Cherry](https://www.adequatelygood.com/).

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Comparison Operators & Equality

[15.1](/content/airbnb/javascript#comparison--eqeqeq/index.html) Use `===` and `!==` over `==` and `!=`. eslint: [`eqeqeq`](https://eslint.org/docs/rules/eqeqeq)

[15.2](/content/airbnb/javascript#comparison--if/index.html) 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](/content/airbnb/javascript#comparison--shortcuts/index.html) 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](/content/airbnb/javascript#comparison--moreinfo/index.html) For more information see [Truth, Equality, and JavaScript](https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll.

[15.5](/content/airbnb/javascript#comparison--switch-blocks/index.html) 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`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#comparison--nested-ternaries/index.html) Ternaries should not be nested and generally be single line expressions. eslint: [`no-nested-ternary`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#comparison--unneeded-ternary/index.html) Avoid unneeded ternary statements. eslint: [`no-unneeded-ternary`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#comparison--no-mixed-operators/index.html) 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`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#nullish-coalescing-operator/index.html) 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`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Blocks

[16.1](/content/airbnb/javascript#blocks--braces/index.html) Use braces with all multiline blocks. eslint: [`nonblock-statement-body-position`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#blocks--cuddled-elses/index.html) 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`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#blocks--no-else-return/index.html) 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`](https://eslint.org/docs/rules/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    }`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Control Statements

[17.1](/content/airbnb/javascript#control-statements/index.html) 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](/content/airbnb/javascript#control-statements--value-selection/index.html) 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    }`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Comments

[18.1](/content/airbnb/javascript#comments--multiline/index.html) 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](/content/airbnb/javascript#comments--singleline/index.html) 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](/content/airbnb/javascript#comments--spaces/index.html) Start all comments with a space to make it easier to read. eslint: [`spaced-comment`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#comments--actionitems/index.html) 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](/content/airbnb/javascript#comments--fixme/index.html) 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](/content/airbnb/javascript#comments--todo/index.html) 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    }`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Whitespace

[19.1](/content/airbnb/javascript#whitespace--spaces/index.html) Use soft tabs (space character) set to 2 spaces. eslint: [`indent`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--before-blocks/index.html) Place 1 space before the leading brace. eslint: [`space-before-blocks`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--around-keywords/index.html) 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`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--infix-ops/index.html) Set off operators with spaces. eslint: [`space-infix-ops`](https://eslint.org/docs/rules/space-infix-ops)

javascript

`1// bad
2    const x=y+5;
3
4    // good
5    const x = y + 5;`

[19.5](/content/airbnb/javascript#whitespace--newline-at-end/index.html) End files with a single newline character. eslint: [`eol-last`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--chains/index.html) 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`](https://eslint.org/docs/rules/newline-per-chained-call) [`no-whitespace-before-property`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--after-blocks/index.html) 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](/content/airbnb/javascript#whitespace--padded-blocks/index.html) Do not pad your blocks with blank lines. eslint: [`padded-blocks`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--no-multiple-blanks/index.html) Do not use multiple blank lines to pad your code. eslint: [`no-multiple-empty-lines`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--in-parens/index.html) Do not add spaces inside parentheses. eslint: [`space-in-parens`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--in-brackets/index.html) Do not add spaces inside brackets. eslint: [`array-bracket-spacing`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--in-braces/index.html) Add spaces inside curly braces. eslint: [`object-curly-spacing`](https://eslint.org/docs/rules/object-curly-spacing)

javascript

`1// bad
2    const foo = {clark: 'kent'};
3
4    // good
5    const foo = { clark: 'kent' };`

[19.13](/content/airbnb/javascript#whitespace--max-len/index.html) Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per [above](/content/airbnb/javascript#strings--line-length/index.html), long strings are exempt from this rule, and should not be broken up. eslint: [`max-len`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--block-spacing/index.html) 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`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--comma-spacing/index.html) Avoid spaces before commas and require a space after commas. eslint: [`comma-spacing`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--computed-property-spacing/index.html) Enforce spacing inside of computed property brackets. eslint: [`computed-property-spacing`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--func-call-spacing/index.html) Avoid spaces between functions and their invocations. eslint: [`func-call-spacing`](https://eslint.org/docs/rules/func-call-spacing)

javascript

`1// bad
2    func ();
3
4    func
5    ();
6
7    // good
8    func();`

[19.18](/content/airbnb/javascript#whitespace--key-spacing/index.html) Enforce spacing between keys and values in object literal properties. eslint: [`key-spacing`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#whitespace--no-trailing-spaces/index.html) Avoid trailing spaces at the end of lines. eslint: [`no-trailing-spaces`](https://eslint.org/docs/rules/no-trailing-spaces)

[19.20](/content/airbnb/javascript#whitespace--no-multiple-empty-lines/index.html) 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`](https://eslint.org/docs/rules/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;`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Commas

[20.1](/content/airbnb/javascript#commas--leading-trailing/index.html) Leading commas: **Nope.** eslint: [`comma-style`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#commas--dangling/index.html) Additional trailing comma: **Yup.** eslint: [`comma-dangle`](https://eslint.org/docs/rules/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](https://github.com/airbnb/javascript/blob/es5-deprecated/es5/README.md#commas) 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    );`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Semicolons

[21.1](/content/airbnb/javascript#semicolons--required/index.html) **Yup.** eslint: [`semi`](https://eslint.org/docs/rules/semi)

\> Why? When JavaScript encounters a line break without a semicolon, it uses a set of rules called [Automatic Semicolon Insertion](https://tc39.github.io/ecma262/#sec-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    }``

[Read more](https://stackoverflow.com/questions/7365172/semicolon-before-self-invoking-function/7365214#7365214).

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Type Casting & Coercion

[22.1](/content/airbnb/javascript#coercion--explicit/index.html) Perform type coercion at the beginning of the statement.

[22.2](/content/airbnb/javascript#coercion--strings/index.html) Strings: eslint: [`no-new-wrappers`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#coercion--numbers/index.html) Numbers: Use `Number` for type casting and `parseInt` always with a radix for parsing strings. eslint: [`radix`](https://eslint.org/docs/rules/radix) [`no-new-wrappers`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#coercion--comment-deviations/index.html) If for whatever reason you are doing something wild and `parseInt` is your bottleneck and need to use Bitshift for [performance reasons](https://web.archive.org/web/20200414205431/https://jsperf.com/coercion-vs-casting/3), 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](/content/airbnb/javascript#coercion--bitwise/index.html) **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](https://es5.github.io/#x4.3.19), but bitshift operations always return a 32-bit integer ( [source](https://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:

javascript

`12147483647 >> 0; // => 2147483647
2    2147483648 >> 0; // => -2147483648
3    2147483649 >> 0; // => -2147483647`

[22.6](/content/airbnb/javascript#coercion--booleans/index.html) Booleans: eslint: [`no-new-wrappers`](https://eslint.org/docs/rules/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;`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Naming Conventions

[23.1](/content/airbnb/javascript#naming--descriptive/index.html) Avoid single letter names. Be descriptive with your naming. eslint: [`id-length`](https://eslint.org/docs/rules/id-length)

javascript

`1// bad
2    function q() {
3      // ...
4    }
5
6    // good
7    function query() {
8      // ...
9    }`

[23.2](/content/airbnb/javascript#naming--camelCase/index.html) Use camelCase when naming objects, functions, and instances. eslint: [`camelcase`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#naming--PascalCase/index.html) Use PascalCase only when naming constructors or classes. eslint: [`new-cap`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#naming--leading-underscore/index.html) Do not use trailing or leading underscores. eslint: [`no-underscore-dangle`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#naming--self-this/index.html) Don’t save references to `this`. Use arrow functions or [Function#bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](/content/airbnb/javascript#naming--filename-matches-export/index.html) 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](/content/airbnb/javascript#naming--camelCase-default-export/index.html) 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](/content/airbnb/javascript#naming--PascalCase-singleton/index.html) 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](/content/airbnb/javascript#naming--Acronyms-and-Initialisms/index.html) 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](/content/airbnb/javascript#naming--uppercase/index.html) 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    };`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Accessors

[24.1](/content/airbnb/javascript#accessors--not-required/index.html) Accessor functions for properties are not required.

[24.2](/content/airbnb/javascript#accessors--no-getters-setters/index.html) 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](/content/airbnb/javascript#accessors--boolean-prefix/index.html) 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](/content/airbnb/javascript#accessors--consistent/index.html) 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    }`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Events

[25.1](/content/airbnb/javascript#events--hash/index.html) 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    });`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## jQuery

[26.1](/content/airbnb/javascript#jquery--dollar-prefix/index.html) 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](/content/airbnb/javascript#jquery--cache/index.html) 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](/content/airbnb/javascript#jquery--queries/index.html) For DOM queries use Cascading `$('.sidebar ul')` or parent > child `$('.sidebar > ul')`. [jsPerf](https://web.archive.org/web/20200414183810/https://jsperf.com/jquery-find-vs-context-sel/16)

[26.4](/content/airbnb/javascript#jquery--find/index.html) 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();`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## ECMAScript 5 Compatibility

[27.1](/content/airbnb/javascript#es5-compat--kangax/index.html) Refer to [Kangax](https://twitter.com/kangax/)’s ES5 [compatibility table](https://compat-table.github.io/compat-table/es5/).

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## ECMAScript 6+ (ES 2015+) Styles

[28.1](/content/airbnb/javascript#es6-styles/index.html) This is a collection of links to the various ES6+ features.

1.

[Arrow Functions](/content/airbnb/javascript#arrow-functions/index.html)

1.

[Classes](/content/airbnb/javascript#classes--constructors/index.html)

1.

[Object Shorthand](/content/airbnb/javascript#es6-object-shorthand/index.html)

1.

[Object Concise](/content/airbnb/javascript#es6-object-concise/index.html)

1.

[Object Computed Properties](/content/airbnb/javascript#es6-computed-properties/index.html)

1.

[Template Strings](/content/airbnb/javascript#es6-template-literals/index.html)

1.

[Destructuring](/content/airbnb/javascript#destructuring/index.html)

1.

[Default Parameters](/content/airbnb/javascript#es6-default-parameters/index.html)

1.

[Rest](/content/airbnb/javascript#es6-rest/index.html)

1.

[Array Spreads](/content/airbnb/javascript#es6-array-spreads/index.html)

1.

[Let and Const](/content/airbnb/javascript#references/index.html)

1.

[Exponentiation Operator](/content/airbnb/javascript#es2016-properties--exponentiation-operator/index.html)

1.

[Iterators and Generators](/content/airbnb/javascript#iterators-and-generators/index.html)

1.

[Modules](/content/airbnb/javascript#modules/index.html)

[28.2](/content/airbnb/javascript#tc39-proposals/index.html) Do not use [TC39 proposals](https://github.com/tc39/proposals) that have not reached stage 3.

\> Why? [They are not finalized](https://tc39.github.io/process-document/), and they are subject to change or to be withdrawn entirely. We want to use JavaScript, and proposals are not JavaScript yet.

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Standard Library

The [Standard Library](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects)

contains utilities that are functionally broken but remain for legacy reasons.

[29.1](/content/airbnb/javascript#standard-library--isnan/index.html) Use `Number.isNaN` instead of global `isNaN`.

eslint: [`no-restricted-globals`](https://eslint.org/docs/rules/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](/content/airbnb/javascript#standard-library--isfinite/index.html) Use `Number.isFinite` instead of global `isFinite`.

eslint: [`no-restricted-globals`](https://eslint.org/docs/rules/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`

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Testing

[30.1](/content/airbnb/javascript#testing--yup/index.html) **Yup.**

javascript

`1function foo() {
2      return true;
3    }`

[30.2](/content/airbnb/javascript#testing--for-real/index.html) **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`](https://www.npmjs.com/package/mocha) and [`jest`](https://www.npmjs.com/package/jest) at Airbnb. [`tape`](https://www.npmjs.com/package/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.

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Performance

[On Layout & Web Performance](https://www.kellegous.com/j/2013/01/26/layout-performance/)

[String vs Array Concat](https://web.archive.org/web/20200414200857/https://jsperf.com/string-vs-array-concat/2)

[Try/Catch Cost In a Loop](https://web.archive.org/web/20200414190827/https://jsperf.com/try-catch-in-loop-cost/12)

[Bang Function](https://web.archive.org/web/20200414205426/https://jsperf.com/bang-function)

[jQuery Find vs Context, Selector](https://web.archive.org/web/20200414200850/https://jsperf.com/jquery-find-vs-context-sel/164)

[innerHTML vs textContent for script text](https://web.archive.org/web/20200414205428/https://jsperf.com/innerhtml-vs-textcontent-for-script-text)

[Long String Concatenation](https://web.archive.org/web/20200414203914/https://jsperf.com/ya-string-concat/38)

[Are JavaScript functions like `map()`, `reduce()`, and `filter()` optimized for traversing arrays?](https://www.quora.com/JavaScript-programming-language-Are-Javascript-functions-like-map-reduce-and-filter-already-optimized-for-traversing-array/answer/Quildreen-Motta)

Loading...

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Resources

**Learning ES6+**

[Latest ECMA spec](https://tc39.github.io/ecma262/)

[ExploringJS](https://exploringjs.com/)

[ES6 Compatibility Table](https://compat-table.github.io/compat-table/es6/)

[Comprehensive Overview of ES6 Features](https://web.archive.org/web/20240404212626/http://es6-features.org/)

[JavaScript Roadmap](https://roadmap.sh/javascript)

**Read This**

[Standard ECMA-262](https://www.ecma-international.org/ecma-262/6.0/index.html)

**Tools**

Code Style Linters

[ESlint](https://eslint.org/) \- [Airbnb Style .eslintrc](https://github.com/airbnb/javascript/blob/master/linters/.eslintrc)

[JSHint](https://jshint.com/) \- [Airbnb Style .jshintrc](https://github.com/airbnb/javascript/blob/master/linters/.jshintrc)

Neutrino Preset - [@neutrinojs/airbnb](https://neutrinojs.org/packages/airbnb/)

**Other Style Guides**

[Google JavaScript Style Guide](https://google.github.io/styleguide/jsguide.html)

[Google JavaScript Style Guide (Old)](https://google.github.io/styleguide/javascriptguide.xml)

[jQuery Core Style Guidelines](https://contribute.jquery.org/style-guide/js/)

[Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwaldron/idiomatic.js)

[StandardJS](https://standardjs.com/)

**Other Styles**

[Naming this in nested functions](https://gist.github.com/cjohansen/4135065) \- Christian Johansen

[Conditional Callbacks](https://github.com/airbnb/javascript/issues/52) \- Ross Allen

[Popular JavaScript Coding Conventions on GitHub](http://sideeffect.kr/popularconvention/#javascript) \- JeongHoon Byun

[Multiple var statements in JavaScript, not superfluous](https://benalman.com/news/2012/05/multiple-var-statements-javascript/) \- Ben Alman

**Further Reading**

[Understanding JavaScript Closures](https://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/) \- Angus Croll

[Basic JavaScript for the impatient programmer](https://www.2ality.com/2013/06/basic-javascript.html) \- Dr. Axel Rauschmayer

[You Might Not Need jQuery](https://youmightnotneedjquery.com/) \- Zack Bloom & Adam Schwartz

[ES6 Features](https://github.com/lukehoban/es6features) \- Luke Hoban

[Frontend Guidelines](https://github.com/bendc/frontend-guidelines) \- Benjamin De Cock

**Books**

[JavaScript: The Good Parts](https://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) \- Douglas Crockford

[JavaScript Patterns](https://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752) \- Stoyan Stefanov

[Pro JavaScript Design Patterns](https://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X) \- Ross Harmes and Dustin Diaz

[High Performance Web Sites: Essential Knowledge for Front-End Engineers](https://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309) \- Steve Souders

[Maintainable JavaScript](https://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680) \- Nicholas C. Zakas

[JavaScript Web Applications](https://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X) \- Alex MacCaw

[Pro JavaScript Techniques](https://www.amazon.com/Pro-JavaScript-Techniques-John-Resig/dp/1590597273) \- John Resig

[Smashing Node.js: JavaScript Everywhere](https://www.amazon.com/Smashing-Node-js-JavaScript-Everywhere-Magazine/dp/1119962595) \- Guillermo Rauch

[Secrets of the JavaScript Ninja](https://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/193398869X) \- John Resig and Bear Bibeault

[Human JavaScript](http://humanjavascript.com/) \- Henrik Joreteg

[Superhero.js](http://superherojs.com/) \- Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy

[JSBooks](https://jsbooks.revolunet.com/) \- Julien Bouquillon

[Third Party JavaScript](https://www.manning.com/books/third-party-javascript) \- Ben Vinegar and Anton Kovalyov

[Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript](https://amzn.com/dp/0321812182) \- David Herman

[Eloquent JavaScript](https://eloquentjavascript.net/) \- Marijn Haverbeke

[You Don’t Know JS: ES6 & Beyond](https://shop.oreilly.com/product/0636920033769.do) \- Kyle Simpson

**Blogs**

[JavaScript Weekly](https://javascriptweekly.com/)

[JavaScript, JavaScript...](https://javascriptweblog.wordpress.com/)

[Bocoup Weblog](https://bocoup.com/weblog)

[Adequately Good](https://www.adequatelygood.com/)

[NCZOnline](https://www.nczonline.net/)

[Perfection Kills](http://perfectionkills.com/)

[Ben Alman](https://benalman.com/)

[Dmitry Baranovskiy](http://dmitry.baranovskiy.com/)

[nettuts](https://code.tutsplus.com/?s=javascript)

**Podcasts**

[JavaScript Air](https://javascriptair.com/)

[JavaScript Jabber](https://devchat.tv/js-jabber/)

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## 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](https://github.com/123erfasst/javascript)

**4Catalyzer**: [4Catalyzer/javascript](https://github.com/4Catalyzer/javascript)

**Aan Zee**: [AanZee/javascript](https://github.com/AanZee/javascript)

**Airbnb**: [airbnb/javascript](https://github.com/airbnb/javascript)

**AloPeyk**: [AloPeyk](https://github.com/AloPeyk)

**AltSchool**: [AltSchool/javascript](https://github.com/AltSchool/javascript)

**Apartmint**: [apartmint/javascript](https://github.com/apartmint/javascript)

**Ascribe**: [ascribe/javascript](https://github.com/ascribe/javascript)

**Avant**: [avantcredit/javascript](https://github.com/avantcredit/javascript)

**Axept**: [axept/javascript](https://github.com/axept/javascript)

**Billabong**: [billabong/javascript](https://github.com/billabong/javascript)

**Bisk**: [bisk](https://github.com/Bisk/)

**Brainshark**: [brainshark/javascript](https://github.com/brainshark/javascript)

**CaseNine**: [CaseNine/javascript](https://github.com/CaseNine/javascript)

**Cerner**: [Cerner](https://github.com/cerner/)

**Chartboost**: [ChartBoost/javascript-style-guide](https://github.com/ChartBoost/javascript-style-guide)

**Coeur d'Alene Tribe**: [www.cdatribe-nsn.gov](https://www.cdatribe-nsn.gov/)

**ComparaOnline**: [comparaonline/javascript](https://github.com/comparaonline/javascript-style-guide)

**Compass Learning**: [compasslearning/javascript-style-guide](https://github.com/compasslearning/javascript-style-guide)

**DailyMotion**: [dailymotion/javascript](https://github.com/dailymotion/javascript)

**DoSomething**: [DoSomething/eslint-config](https://github.com/DoSomething/eslint-config)

**Digitpaint** [digitpaint/javascript](https://github.com/digitpaint/javascript)

**Drupal**: [www.drupal.org](https://git.drupalcode.org/project/drupal/blob/8.6.x/core/.eslintrc.json)

**Ecosia**: [ecosia/javascript](https://github.com/ecosia/javascript)

**Evolution Gaming**: [evolution-gaming/javascript](https://github.com/evolution-gaming/javascript)

**EvozonJs**: [evozonjs/javascript](https://github.com/evozonjs/javascript)

**ExactTarget**: [ExactTarget/javascript](https://github.com/ExactTarget/javascript)

**Flexberry**: [Flexberry/javascript-style-guide](https://github.com/Flexberry/javascript-style-guide)

**Gawker Media**: [gawkermedia](https://github.com/gawkermedia/)

**General Electric**: [GeneralElectric/javascript](https://github.com/GeneralElectric/javascript)

**Generation Tux**: [GenerationTux/javascript](https://github.com/generationtux/styleguide)

**GoodData**: [gooddata/gdc-js-style](https://github.com/gooddata/gdc-js-style)

**GreenChef**: [greenchef/javascript](https://github.com/greenchef/javascript)

**Grooveshark**: [grooveshark/javascript](https://github.com/grooveshark/javascript)

**Grupo-Abraxas**: [Grupo-Abraxas/javascript](https://github.com/Grupo-Abraxas/javascript)

**Happeo**: [happeo/javascript](https://github.com/happeo/javascript)

**How About We**: [howaboutwe/javascript](https://github.com/howaboutwe/javascript-style-guide)

**HubSpot**: [HubSpot/javascript](https://github.com/HubSpot/javascript)

**Hyper**: [hyperoslo/javascript-playbook](https://github.com/hyperoslo/javascript-playbook/blob/master/style.md)

**ILIAS**: [ILIAS](https://github.com/ILIAS-eLearning/ILIAS)

**InterCity Group**: [intercitygroup/javascript-style-guide](https://github.com/intercitygroup/javascript-style-guide)

**Jam3**: [Jam3/Javascript-Code-Conventions](https://github.com/Jam3/Javascript-Code-Conventions)

**JSSolutions**: [JSSolutions/javascript](https://github.com/JSSolutions/javascript)

**Kaplan Komputing**: [kaplankomputing/javascript](https://github.com/kaplankomputing/javascript)

**KickorStick**: [kickorstick](https://github.com/kickorstick/)

**Kinetica Solutions**: [kinetica/javascript](https://github.com/kinetica/Javascript-style-guide)

**LEINWAND**: [LEINWAND/javascript](https://github.com/LEINWAND/javascript)

**Lonely Planet**: [lonelyplanet/javascript](https://github.com/lonelyplanet/javascript)

**M2GEN**: [M2GEN/javascript](https://github.com/M2GEN/javascript)

**Mighty Spring**: [mightyspring/javascript](https://github.com/mightyspring/javascript)

**MinnPost**: [MinnPost/javascript](https://github.com/MinnPost/javascript)

**MitocGroup**: [MitocGroup/javascript](https://github.com/MitocGroup/javascript)

**Muber**: [muber](https://github.com/muber/)

**National Geographic Society**: [natgeosociety](https://github.com/natgeosociety/)

**NullDev**: [NullDevCo/JavaScript-Styleguide](https://github.com/NullDevCo/JavaScript-Styleguide)

**Nulogy**: [nulogy/javascript](https://github.com/nulogy/javascript)

**Orange Hill Development**: [orangehill/javascript](https://github.com/orangehill/javascript)

**Orion Health**: [orionhealth/javascript](https://github.com/orionhealth/javascript)

**Peerby**: [Peerby/javascript](https://github.com/Peerby/javascript)

**Pier 1**: [Pier1/javascript](https://github.com/pier1/javascript)

**Qotto**: [Qotto/javascript-style-guide](https://github.com/Qotto/javascript-style-guide)

**React**: [reactjs.org/docs/how-to-contribute.html#style-guide](https://reactjs.org/docs/how-to-contribute.html#style-guide)

**Ripple**: [ripple/javascript-style-guide](https://github.com/ripple/javascript-style-guide)

**Sainsbury’s Supermarkets**: [jsainsburyplc](https://github.com/jsainsburyplc)

**Shutterfly**: [shutterfly/javascript](https://github.com/shutterfly/javascript)

**Sourcetoad**: [sourcetoad/javascript](https://github.com/sourcetoad/javascript)

**Springload**: [springload](https://github.com/springload/)

**StratoDem Analytics**: [stratodem/javascript](https://github.com/stratodem/javascript)

**SteelKiwi Development**: [steelkiwi/javascript](https://github.com/steelkiwi/javascript)

**StudentSphere**: [studentsphere/javascript](https://github.com/studentsphere/guide-javascript)

**SwoopApp**: [swoopapp/javascript](https://github.com/swoopapp/javascript)

**SysGarage**: [sysgarage/javascript-style-guide](https://github.com/sysgarage/javascript-style-guide)

**Syzygy Warsaw**: [syzygypl/javascript](https://github.com/syzygypl/javascript)

**Target**: [target/javascript](https://github.com/target/javascript)

**Terra**: [terra](https://github.com/cerner?utf8=%E2%9C%93&q=terra&type=&language=)

**TheLadders**: [TheLadders/javascript](https://github.com/TheLadders/javascript)

**The Nerdery**: [thenerdery/javascript-standards](https://github.com/thenerdery/javascript-standards)

**Tomify**: [tomprats](https://github.com/tomprats)

**Traitify**: [traitify/eslint-config-traitify](https://github.com/traitify/eslint-config-traitify)

**T4R Technology**: [T4R-Technology/javascript](https://github.com/T4R-Technology/javascript)

**UrbanSim**: [urbansim](https://github.com/urbansim/)

**VoxFeed**: [VoxFeed/javascript-style-guide](https://github.com/VoxFeed/javascript-style-guide)

**WeBox Studio**: [weboxstudio/javascript](https://github.com/weboxstudio/javascript)

**Weggo**: [Weggo/javascript](https://github.com/Weggo/javascript)

**Zillow**: [zillow/javascript](https://github.com/zillow/javascript)

**Zit Software**: [zit-software/javascript](https://github.com/zit-software/javascript)

**ZocDoc**: [ZocDoc/javascript](https://github.com/ZocDoc/javascript)

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## Translation

This style guide is also available in other languages:

**Brazilian Portuguese**: [armoucar/javascript-style-guide](https://github.com/armoucar/javascript-style-guide)

**Bulgarian**: [borislavvv/javascript](https://github.com/borislavvv/javascript)

**Catalan**: [fpmweb/javascript-style-guide](https://github.com/fpmweb/javascript-style-guide)

**Chinese (Simplified)**: [lin-123/javascript](https://github.com/lin-123/javascript)

**Chinese (Traditional)**: [jigsawye/javascript](https://github.com/jigsawye/javascript)

**French**: [nmussy/javascript-style-guide](https://github.com/nmussy/javascript-style-guide)

**German**: [timofurrer/javascript-style-guide](https://github.com/timofurrer/javascript-style-guide)

**Italian**: [sinkswim/javascript-style-guide](https://github.com/sinkswim/javascript-style-guide)

**Japanese**: [mitsuruog/javascript-style-guide](https://github.com/mitsuruog/javascript-style-guide)

**Korean**: [ParkSB/javascript-style-guide](https://github.com/ParkSB/javascript-style-guide)

**Russian**: [leonidlebedev/javascript-airbnb](https://github.com/leonidlebedev/javascript-airbnb)

**Spanish**: [paolocarrasco/javascript-style-guide](https://github.com/paolocarrasco/javascript-style-guide)

**Thai**: [lvarayut/javascript-style-guide](https://github.com/lvarayut/javascript-style-guide)

**Turkish**: [eraycetinay/javascript](https://github.com/eraycetinay/javascript)

**Ukrainian**: [ivanzusko/javascript](https://github.com/ivanzusko/javascript)

**Vietnam**: [dangkyokhoang/javascript-style-guide](https://github.com/dangkyokhoang/javascript-style-guide)

## The JavaScript Style Guide Guide

[Reference](https://github.com/airbnb/javascript/wiki/The-JavaScript-Style-Guide-Guide)

## Chat With Us About JavaScript

Find us on [gitter](https://gitter.im/airbnb/javascript).

## Contributors

[View Contributors](https://github.com/airbnb/javascript/graphs/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.

**[⬆ back to top](/content/airbnb/javascript#table-of-contents/index.html)**

## 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
