Airbnb Style Guide

JavaScript Style Guide

README

Airbnb JavaScript Style Guide


A mostly reasonable approach to JavaScript

Note: this guide assumes you are using Babel, and requires that you use babel-preset-airbnb or the equivalent. It also assumes you are installing shims/polyfills in your app, with airbnb-browser-shims or the equivalent.

Downloads Downloads Gitter

This guide is available in other languages too. See Translation

Other Style Guides

  - React
  - Ruby

Types


  - 1.1Primitives: When you access a primitive type you work directly on its value.

    - string
    - number
    - boolean
    - null
    - undefined
    - symbol
    - bigint

  1. ``` js
  2.     const foo = 1;
  3.     let bar = foo;

  4.     bar = 9;

  5.     console.log(foo, bar); // => 1, 9
  6. ```

    - Symbols and BigInts cannot be faithfully polyfilled, so they should not be used when targeting browsers/environments that don’t support them natively.

  - 1.2Complex: When you access a complex type you work on a reference to its value.

    - object
    - array
    - function

  1. ``` js
  2.     const foo = [1, 2];
  3.     const bar = foo;

  4.     bar[0] = 9;

  5.     console.log(foo[0], bar[0]); // => 9, 9
  6. ```


References


  - 2.1 Useconst 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.

  1. ``` js
  2.     // bad
  3.     var a = 1;
  4.     var b = 2;

  5.     // good
  6.     const a = 1;
  7.     const b = 2;
  8. ```

  - 2.2 If you must reassign references, uselet instead of var. eslint: [no-var](https://eslint.org/docs/rules/no-var)

    > Why? let is block-scoped rather than function-scoped like var.

  1. ``` js
  2.     // bad
  3.     var count = 1;
  4.     if (true) {
  5.       count += 1;
  6.     }

  7.     // good, use the let.
  8.     let count = 1;
  9.     if (true) {
  10.       count += 1;
  11.     }
  12. ```

  - 2.3 Note that bothlet and const are block-scoped, whereas var is function-scoped.

  1. ``` js
  2.     // const and let only exist in the blocks they are defined in.
  3.     {
  4.       let a = 1;
  5.       const b = 1;
  6.       var c = 1;
  7.     }
  8.     console.log(a); // ReferenceError
  9.     console.log(b); // ReferenceError
  10.     console.log(c); // Prints 1
  11. ```

    In the above code, you can see that referencing a and b will produce a ReferenceError, while c contains the number. This is because a and b are block scoped, while c is scoped to the containing function.


Objects


  - 3.1 Use the literal syntax for object creation. eslint: [no-new-object](https://eslint.org/docs/rules/no-new-object)

  1. ``` js
  2.     // bad
  3.     const item = new Object();

  4.     // good
  5.     const item = {};
  6. ```

  - 3.2 Use computed property names when creating objects with dynamic property names.

    > Why? They allow you to define all the properties of an object in one place.

  1. ``` js

  2.     function getKey(k) {
  3.       return `a key named ${k}`;
  4.     }

  5.     // bad
  6.     const obj = {
  7.       id: 5,
  8.       name: 'San Francisco',
  9.     };
  10.     obj[getKey('enabled')] = true;

  11.     // good
  12.     const obj = {
  13.       id: 5,
  14.       name: 'San Francisco',
  15.       [getKey('enabled')]: true,
  16.     };
  17. ```

  - 3.3 Use object method shorthand. eslint: [object-shorthand](https://eslint.org/docs/rules/object-shorthand)

  1. ``` js
  2.     // bad
  3.     const atom = {
  4.       value: 1,

  5.       addValue: function (value) {
  6.         return atom.value + value;
  7.       },
  8.     };

  9.     // good
  10.     const atom = {
  11.       value: 1,

  12.       addValue(value) {
  13.         return atom.value + value;
  14.       },
  15.     };
  16. ```

  - 3.4 Use property value shorthand. eslint: [object-shorthand](https://eslint.org/docs/rules/object-shorthand)

    > Why? It is shorter and descriptive.

  1. ``` js
  2.     const lukeSkywalker = 'Luke Skywalker';

  3.     // bad
  4.     const obj = {
  5.       lukeSkywalker: lukeSkywalker,
  6.     };

  7.     // good
  8.     const obj = {
  9.       lukeSkywalker,
  10.     };
  11. ```

  - 3.5 Group your shorthand properties at the beginning of your object declaration.

    > Why? It’s easier to tell which properties are using the shorthand.

  1. ``` js
  2.     const anakinSkywalker = 'Anakin Skywalker';
  3.     const lukeSkywalker = 'Luke Skywalker';

  4.     // bad
  5.     const obj = {
  6.       episodeOne: 1,
  7.       twoJediWalkIntoACantina: 2,
  8.       lukeSkywalker,
  9.       episodeThree: 3,
  10.       mayTheFourth: 4,
  11.       anakinSkywalker,
  12.     };

  13.     // good
  14.     const obj = {
  15.       lukeSkywalker,
  16.       anakinSkywalker,
  17.       episodeOne: 1,
  18.       twoJediWalkIntoACantina: 2,
  19.       episodeThree: 3,
  20.       mayTheFourth: 4,
  21.     };
  22. ```

  - 3.6 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.

  1. ``` js
  2.     // bad
  3.     const bad = {
  4.       'foo': 3,
  5.       'bar': 4,
  6.       'data-blah': 5,
  7.     };

  8.     // good
  9.     const good = {
  10.       foo: 3,
  11.       bar: 4,
  12.       'data-blah': 5,
  13.     };
  14. ```

  - 3.7 Do not callObject.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)).

  1. ``` js
  2.     // bad
  3.     console.log(object.hasOwnProperty(key));

  4.     // good
  5.     console.log(Object.prototype.hasOwnProperty.call(object, key));

  6.     // best
  7.     const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
  8.     console.log(has.call(object, key));
  9.     /* or */
  10.     import has from 'has'; // https://www.npmjs.com/package/has
  11.     console.log(has(object, key));
  12. ```

  - 3.8 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)

  1. ``` js
  2.     // very bad
  3.     const original = { a: 1, b: 2 };
  4.     const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ
  5.     delete copy.a; // so does this

  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.     // good
  10.     const original = { a: 1, b: 2 };
  11.     const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }

  12.     const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
  13. ```


Arrays


  - 4.1 Use the literal syntax for array creation. eslint: [no-array-constructor](https://eslint.org/docs/rules/no-array-constructor)

  1. ``` js
  2.     // bad
  3.     const items = new Array();

  4.     // good
  5.     const items = [];
  6. ```

  - 4.2 Use Array#push instead of direct assignment to add items to an array.

  1. ``` js
  2.     const someStack = [];

  3.     // bad
  4.     someStack[someStack.length] = 'abracadabra';

  5.     // good
  6.     someStack.push('abracadabra');
  7. ```

  - 4.3 Use array spreads... to copy arrays.

  1. ``` js
  2.     // bad
  3.     const len = items.length;
  4.     const itemsCopy = [];
  5.     let i;

  6.     for (i = 0; i < len; i += 1) {
  7.       itemsCopy[i] = items[i];
  8.     }

  9.     // good
  10.     const itemsCopy = [...items];
  11. ```

  - 4.4 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)

  1. ``` js
  2.     const foo = document.querySelectorAll('.foo');

  3.     // good
  4.     const nodes = Array.from(foo);

  5.     // best
  6.     const nodes = [...foo];
  7. ```

  - 4.5 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.

  1. ``` js
  2.     const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };

  3.     // bad
  4.     const arr = Array.prototype.slice.call(arrLike);

  5.     // good
  6.     const arr = Array.from(arrLike);
  7. ```

  - 4.6 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.

  1. ``` js
  2.     // bad
  3.     const baz = [...foo].map(bar);

  4.     // good
  5.     const baz = Array.from(foo, bar);
  6. ```

  - 4.7 Use return statements in array method callbacks. It’s ok to omit the return if the function body consists of a single statement returning an expression without side effects, following 8.2. eslint: [array-callback-return](https://eslint.org/docs/rules/array-callback-return)

  1. ``` js
  2.     // good
  3.     [1, 2, 3].map((x) => {
  4.       const y = x + 1;
  5.       return x * y;
  6.     });

  7.     // good
  8.     [1, 2, 3].map((x) => x + 1);

  9.     // bad - no returned value means `acc` becomes undefined after the first iteration
  10.     [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
  11.       const flatten = acc.concat(item);
  12.     });

  13.     // good
  14.     [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
  15.       const flatten = acc.concat(item);
  16.       return flatten;
  17.     });

  18.     // bad
  19.     inbox.filter((msg) => {
  20.       const { subject, author } = msg;
  21.       if (subject === 'Mockingbird') {
  22.         return author === 'Harper Lee';
  23.       } else {
  24.         return false;
  25.       }
  26.     });

  27.     // good
  28.     inbox.filter((msg) => {
  29.       const { subject, author } = msg;
  30.       if (subject === 'Mockingbird') {
  31.         return author === 'Harper Lee';
  32.       }

  33.       return false;
  34.     });
  35. ```

  - 4.8 Use line breaks after open and before close array brackets if an array has multiple lines

  1. ``` js
  2.     // bad
  3.     const arr = [
  4.       [0, 1], [2, 3], [4, 5],
  5.     ];

  6.     const objectInArray = [{
  7.       id: 1,
  8.     }, {
  9.       id: 2,
  10.     }];

  11.     const numberInArray = [
  12.       1, 2,
  13.     ];

  14.     // good
  15.     const arr = [[0, 1], [2, 3], [4, 5]];

  16.     const objectInArray = [
  17.       {
  18.         id: 1,
  19.       },
  20.       {
  21.         id: 2,
  22.       },
  23.     ];

  24.     const numberInArray = [
  25.       1,
  26.       2,
  27.     ];
  28. ```


Destructuring


  - 5.1 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.

  1. ``` js
  2.     // bad
  3.     function getFullName(user) {
  4.       const firstName = user.firstName;
  5.       const lastName = user.lastName;

  6.       return `${firstName} ${lastName}`;
  7.     }

  8.     // good
  9.     function getFullName(user) {
  10.       const { firstName, lastName } = user;
  11.       return `${firstName} ${lastName}`;
  12.     }

  13.     // best
  14.     function getFullName({ firstName, lastName }) {
  15.       return `${firstName} ${lastName}`;
  16.     }
  17. ```

  - 5.2 Use array destructuring. eslint: [prefer-destructuring](https://eslint.org/docs/rules/prefer-destructuring)

  1. ``` js
  2.     const arr = [1, 2, 3, 4];

  3.     // bad
  4.     const first = arr[0];
  5.     const second = arr[1];

  6.     // good
  7.     const [first, second] = arr;
  8. ```

  - 5.3 Use object destructuring for multiple return values, not array destructuring.

    > Why? You can add new properties over time or change the order of things without breaking call sites.

  1. ``` js
  2.     // bad
  3.     function processInput(input) {
  4.       // then a miracle occurs
  5.       return [left, right, top, bottom];
  6.     }

  7.     // the caller needs to think about the order of return data
  8.     const [left, __, top] = processInput(input);

  9.     // good
  10.     function processInput(input) {
  11.       // then a miracle occurs
  12.       return { left, right, top, bottom };
  13.     }

  14.     // the caller selects only the data they need
  15.     const { left, top } = processInput(input);
  16. ```


Strings


  - 6.1 Use single quotes'' for strings. eslint: [quotes](https://eslint.org/docs/rules/quotes)

  1. ``` js
  2.     // bad
  3.     const name = "Capt. Janeway";

  4.     // bad - template literals should contain interpolation or newlines
  5.     const name = `Capt. Janeway`;

  6.     // good
  7.     const name = 'Capt. Janeway';
  8. ```

  - 6.2 Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation.

    > Why? Broken strings are painful to work with and make code less searchable.

  1. ``` js
  2.     // bad
  3.     const errorMessage = 'This is a super long error that was thrown because \
  4.     of Batman. When you stop to think about how Batman had anything to do \
  5.     with this, you would get nowhere \
  6.     fast.';

  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.     // good
  12.     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.';
  13. ```

  - 6.3 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.

  1. ``` js
  2.     // bad
  3.     function sayHi(name) {
  4.       return 'How are you, ' + name + '?';
  5.     }

  6.     // bad
  7.     function sayHi(name) {
  8.       return ['How are you, ', name, '?'].join();
  9.     }

  10.     // bad
  11.     function sayHi(name) {
  12.       return `How are you, ${ name }?`;
  13.     }

  14.     // good
  15.     function sayHi(name) {
  16.       return `How are you, ${name}?`;
  17.     }
  18. ```

  - 6.4 Never useeval() on a string, it opens too many vulnerabilities. eslint: [no-eval](https://eslint.org/docs/rules/no-eval)

  - 6.5 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.

  1. ``` js
  2.     // bad
  3.     const foo = '\'this\' \i\s \"quoted\"';

  4.     // good
  5.     const foo = '\'this\' is "quoted"';
  6.     const foo = `my name is '${name}'`;
  7. ```


Functions


  - 7.1 Use named function expressions instead of function declarations. eslint: [func-style](https://eslint.org/docs/rules/func-style)

    > Why? Function declarations are hoisted, which means that it’s easy - too easy - to reference the function before it is defined in the file. This harms readability and maintainability. If you find that a function’s definition is large or complex enough that it is interfering with understanding the rest of the file, then perhaps it’s time to extract it to its own module! Don’t forget to explicitly name the expression, regardless of whether or not the name is inferred from the containing variable (which is often the case in modern browsers or when using compilers such as Babel). This eliminates any assumptions made about the Error’s call stack. (Discussion)

  1. ``` js
  2.     // bad
  3.     function foo() {
  4.       // ...
  5.     }

  6.     // bad
  7.     const foo = function () {
  8.       // ...
  9.     };

  10.     // good
  11.     // lexical name distinguished from the variable-referenced invocation(s)
  12.     const short = function longUniqueMoreDescriptiveLexicalFoo() {
  13.       // ...
  14.     };
  15. ```

  - 7.2 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.

  1. ``` js
  2.     // immediately-invoked function expression (IIFE)
  3.     (function () {
  4.       console.log('Welcome to the Internet. Please follow me.');
  5.     }());
  6. ```

  - 7.3 Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears. eslint: [no-loop-func](https://eslint.org/docs/rules/no-loop-func)

  - 7.4Note: ECMA-262 defines a block as a list of statements. A function declaration is not a statement.

  1. ``` js
  2.     // bad
  3.     if (currentUser) {
  4.       function test() {
  5.         console.log('Nope.');
  6.       }
  7.     }

  8.     // good
  9.     let test;
  10.     if (currentUser) {
  11.       test = () => {
  12.         console.log('Yup.');
  13.       };
  14.     }
  15. ```

  - 7.5 Never name a parameterarguments. This will take precedence over the arguments object that is given to every function scope.

  1. ``` js
  2.     // bad
  3.     function foo(name, options, arguments) {
  4.       // ...
  5.     }

  6.     // good
  7.     function foo(name, options, args) {
  8.       // ...
  9.     }
  10. ```

  - 7.6 Never usearguments, 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.

  1. ``` js
  2.     // bad
  3.     function concatenateAll() {
  4.       const args = Array.prototype.slice.call(arguments);
  5.       return args.join('');
  6.     }

  7.     // good
  8.     function concatenateAll(...args) {
  9.       return args.join('');
  10.     }
  11. ```

  - 7.7 Use default parameter syntax rather than mutating function arguments.

  1. ``` js
  2.     // really bad
  3.     function handleThings(opts) {
  4.       // No! We shouldn’t mutate function arguments.
  5.       // Double bad: if opts is falsy it'll be set to an object which may
  6.       // be what you want but it can introduce subtle bugs.
  7.       opts = opts || {};
  8.       // ...
  9.     }

  10.     // still bad
  11.     function handleThings(opts) {
  12.       if (opts === void 0) {
  13.         opts = {};
  14.       }
  15.       // ...
  16.     }

  17.     // good
  18.     function handleThings(opts = {}) {
  19.       // ...
  20.     }
  21. ```

  - 7.8 Avoid side effects with default parameters.

    > Why? They are confusing to reason about.

  1. ``` js
  2.     let b = 1;
  3.     // bad
  4.     function count(a = b++) {
  5.       console.log(a);
  6.     }
  7.     count();  // 1
  8.     count();  // 2
  9.     count(3); // 3
  10.     count();  // 3
  11. ```

  - 7.9 Always put default parameters last. eslint: [default-param-last](https://eslint.org/docs/rules/default-param-last)

  1. ``` js
  2.     // bad
  3.     function handleThings(opts = {}, name) {
  4.       // ...
  5.     }

  6.     // good
  7.     function handleThings(name, opts = {}) {
  8.       // ...
  9.     }
  10. ```

  - 7.10 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.

  1. ``` js
  2.     // bad
  3.     const add = new Function('a', 'b', 'return a + b');

  4.     // still bad
  5.     const subtract = Function('a', 'b', 'return a - b');
  6. ```

  - 7.11 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.

  1. ``` js
  2.     // bad
  3.     const f = function(){};
  4.     const g = function (){};
  5.     const h = function() {};

  6.     // good
  7.     const x = function () {};
  8.     const y = function a() {};
  9. ```

  - 7.12 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.

  1. ``` js
  2.     // bad
  3.     function f1(obj) {
  4.       obj.key = 1;
  5.     }

  6.     // good
  7.     function f2(obj) {
  8.       const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;
  9.     }
  10. ```

  - 7.13 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.

  1. ``` js
  2.     // bad
  3.     function f1(a) {
  4.       a = 1;
  5.       // ...
  6.     }

  7.     function f2(a) {
  8.       if (!a) { a = 1; }
  9.       // ...
  10.     }

  11.     // good
  12.     function f3(a) {
  13.       const b = a || 1;
  14.       // ...
  15.     }

  16.     function f4(a = 1) {
  17.       // ...
  18.     }
  19. ```

  - 7.14 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.

  1. ``` js
  2.     // bad
  3.     const x = [1, 2, 3, 4, 5];
  4.     console.log.apply(console, x);

  5.     // good
  6.     const x = [1, 2, 3, 4, 5];
  7.     console.log(...x);

  8.     // bad
  9.     new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));

  10.     // good
  11.     new Date(...[2016, 8, 5]);
  12. ```

  - 7.15 Functions with multiline signatures, or invocations, should be indented just like every other multiline list in this guide: with each item on a line by itself, with a trailing comma on the last item. eslint: [function-paren-newline](https://eslint.org/docs/rules/function-paren-newline)

  1. ``` js
  2.     // bad
  3.     function foo(bar,
  4.                  baz,
  5.                  quux) {
  6.       // ...
  7.     }

  8.     // good
  9.     function foo(
  10.       bar,
  11.       baz,
  12.       quux,
  13.     ) {
  14.       // ...
  15.     }

  16.     // bad
  17.     console.log(foo,
  18.       bar,
  19.       baz);

  20.     // good
  21.     console.log(
  22.       foo,
  23.       bar,
  24.       baz,
  25.     );
  26. ```


Arrow Functions


  - 8.1 When you must use an anonymous function (as when passing an inline callback), use arrow function notation. eslint: [prefer-arrow-callback](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.

  1. ``` js
  2.     // bad
  3.     [1, 2, 3].map(function (x) {
  4.       const y = x + 1;
  5.       return x * y;
  6.     });

  7.     // good
  8.     [1, 2, 3].map((x) => {
  9.       const y = x + 1;
  10.       return x * y;
  11.     });
  12. ```

  - 8.2 If the function body consists of a single statement returning an expression without side effects, omit the braces and use the implicit return. Otherwise, keep the braces and use areturn 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.

  1. ``` js
  2.     // bad
  3.     [1, 2, 3].map((number) => {
  4.       const nextNumber = number + 1;
  5.       `A string containing the ${nextNumber}.`;
  6.     });

  7.     // good
  8.     [1, 2, 3].map((number) => `A string containing the ${number + 1}.`);

  9.     // good
  10.     [1, 2, 3].map((number) => {
  11.       const nextNumber = number + 1;
  12.       return `A string containing the ${nextNumber}.`;
  13.     });

  14.     // good
  15.     [1, 2, 3].map((number, index) => ({
  16.       [index]: number,
  17.     }));

  18.     // No implicit return with side effects
  19.     function foo(callback) {
  20.       const val = callback();
  21.       if (val === true) {
  22.         // Do something if callback returns true
  23.       }
  24.     }

  25.     let bool = false;

  26.     // bad
  27.     foo(() => bool = true);

  28.     // good
  29.     foo(() => {
  30.       bool = true;
  31.     });
  32. ```

  - 8.3 In case the expression spans over multiple lines, wrap it in parentheses for better readability.

    > Why? It shows clearly where the function starts and ends.

  1. ``` js
  2.     // bad
  3.     ['get', 'post', 'put'].map((httpMethod) => Object.prototype.hasOwnProperty.call(
  4.         httpMagicObjectWithAVeryLongName,
  5.         httpMethod,
  6.       )
  7.     );

  8.     // good
  9.     ['get', 'post', 'put'].map((httpMethod) => (
  10.       Object.prototype.hasOwnProperty.call(
  11.         httpMagicObjectWithAVeryLongName,
  12.         httpMethod,
  13.       )
  14.     ));
  15. ```

  - 8.4 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.

  1. ``` js
  2.     // bad
  3.     [1, 2, 3].map(x => x * x);

  4.     // good
  5.     [1, 2, 3].map((x) => x * x);

  6.     // bad
  7.     [1, 2, 3].map(number => (
  8.       `A long string with the ${number}. Its so long that we dont want it to take up space on the .map line!`
  9.     ));

  10.     // good
  11.     [1, 2, 3].map((number) => (
  12.       `A long string with the ${number}. Its so long that we dont want it to take up space on the .map line!`
  13.     ));

  14.     // bad
  15.     [1, 2, 3].map(x => {
  16.       const y = x + 1;
  17.       return x * y;
  18.     });

  19.     // good
  20.     [1, 2, 3].map((x) => {
  21.       const y = x + 1;
  22.       return x * y;
  23.     });
  24. ```

- [8.5](#arrows--confusing) Avoid confusing arrow function syntax (`=>`) with comparison operators (`<=`, `>=`). eslint: [`no-confusing-arrow`](https://eslint.org/docs/rules/no-confusing-arrow)

  1. ``` js
  2.     // bad
  3.     const itemHeight = (item) => item.height <= 256 ? item.largeSize : item.smallSize;

  4.     // bad
  5.     const itemHeight = (item) => item.height >= 256 ? item.largeSize : item.smallSize;

  6.     // good
  7.     const itemHeight = (item) => (item.height <= 256 ? item.largeSize : item.smallSize);

  8.     // good
  9.     const itemHeight = (item) => {
  10.       const { height, largeSize, smallSize } = item;
  11.       return height <= 256 ? largeSize : smallSize;
  12.     };
  13. ```

  - 8.6 Enforce the location of arrow function bodies with implicit returns. eslint: [implicit-arrow-linebreak](https://eslint.org/docs/rules/implicit-arrow-linebreak)

  1. ``` js
  2.     // bad
  3.     (foo) =>
  4.       bar;

  5.     (foo) =>
  6.       (bar);

  7.     // good
  8.     (foo) => bar;
  9.     (foo) => (bar);
  10.     (foo) => (
  11.        bar
  12.     )
  13. ```


Classes & Constructors


  - 9.1 Always useclass. Avoid manipulating prototype directly.

    > Why? class syntax is more concise and easier to reason about.

  1. ``` js
  2.     // bad
  3.     function Queue(contents = []) {
  4.       this.queue = [...contents];
  5.     }
  6.     Queue.prototype.pop = function () {
  7.       const value = this.queue[0];
  8.       this.queue.splice(0, 1);
  9.       return value;
  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.     }
  22. ```

  - 9.2 Useextends for inheritance.

    > Why? It is a built-in way to inherit prototype functionality without breaking instanceof.

  1. ``` js
  2.     // bad
  3.     const inherits = require('inherits');
  4.     function PeekableQueue(contents) {
  5.       Queue.apply(this, contents);
  6.     }
  7.     inherits(PeekableQueue, Queue);
  8.     PeekableQueue.prototype.peek = function () {
  9.       return this.queue[0];
  10.     };

  11.     // good
  12.     class PeekableQueue extends Queue {
  13.       peek() {
  14.         return this.queue[0];
  15.       }
  16.     }
  17. ```

  - 9.3 Methods can returnthis to help with method chaining.

  1. ``` js
  2.     // bad
  3.     Jedi.prototype.jump = function () {
  4.       this.jumping = true;
  5.       return true;
  6.     };

  7.     Jedi.prototype.setHeight = function (height) {
  8.       this.height = height;
  9.     };

  10.     const luke = new Jedi();
  11.     luke.jump(); // => true
  12.     luke.setHeight(20); // => undefined

  13.     // good
  14.     class Jedi {
  15.       jump() {
  16.         this.jumping = true;
  17.         return this;
  18.       }

  19.       setHeight(height) {
  20.         this.height = height;
  21.         return this;
  22.       }
  23.     }

  24.     const luke = new Jedi();

  25.     luke.jump()
  26.       .setHeight(20);
  27. ```

  - 9.4 It’s okay to write a customtoString() method, just make sure it works successfully and causes no side effects.

  1. ``` js
  2.     class Jedi {
  3.       constructor(options = {}) {
  4.         this.name = options.name || 'no name';
  5.       }

  6.       getName() {
  7.         return this.name;
  8.       }

  9.       toString() {
  10.         return `Jedi - ${this.getName()}`;
  11.       }
  12.     }
  13. ```

  - 9.5 Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary. eslint: [no-useless-constructor](https://eslint.org/docs/rules/no-useless-constructor)

  1. ``` js
  2.     // bad
  3.     class Jedi {
  4.       constructor() {}

  5.       getName() {
  6.         return this.name;
  7.       }
  8.     }

  9.     // bad
  10.     class Rey extends Jedi {
  11.       constructor(...args) {
  12.         super(...args);
  13.       }
  14.     }

  15.     // good
  16.     class Rey extends Jedi {
  17.       constructor(...args) {
  18.         super(...args);
  19.         this.name = 'Rey';
  20.       }
  21.     }
  22. ```

  - 9.6 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.

  1. ``` js
  2.     // bad
  3.     class Foo {
  4.       bar() { return 1; }
  5.       bar() { return 2; }
  6.     }

  7.     // good
  8.     class Foo {
  9.       bar() { return 1; }
  10.     }

  11.     // good
  12.     class Foo {
  13.       bar() { return 2; }
  14.     }
  15. ```

  - 9.7 Class methods should usethis 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)

  1. ``` js
  2.     // bad
  3.     class Foo {
  4.       bar() {
  5.         console.log('bar');
  6.       }
  7.     }

  8.     // good - this is used
  9.     class Foo {
  10.       bar() {
  11.         console.log(this.bar);
  12.       }
  13.     }

  14.     // good - constructor is exempt
  15.     class Foo {
  16.       constructor() {
  17.         // ...
  18.       }
  19.     }

  20.     // good - static methods aren't expected to use this
  21.     class Foo {
  22.       static bar() {
  23.         console.log('bar');
  24.       }
  25.     }
  26. ```


Modules


  - 10.1 Always use modules (import/export) over a non-standard module system. You can always transpile to your preferred module system.

    > Why? Modules are the future, let’s start using the future now.

  1. ``` js
  2.     // bad
  3.     const AirbnbStyleGuide = require('./AirbnbStyleGuide');
  4.     module.exports = AirbnbStyleGuide.es6;

  5.     // ok
  6.     import AirbnbStyleGuide from './AirbnbStyleGuide';
  7.     export default AirbnbStyleGuide.es6;

  8.     // best
  9.     import { es6 } from './AirbnbStyleGuide';
  10.     export default es6;
  11. ```

  - 10.2 Do not use wildcard imports.

    > Why? This makes sure you have a single default export.

  1. ``` js
  2.     // bad
  3.     import * as AirbnbStyleGuide from './AirbnbStyleGuide';

  4.     // good
  5.     import AirbnbStyleGuide from './AirbnbStyleGuide';
  6. ```

  - 10.3 And do not export directly from an import.

    > Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.

  1. ``` js
  2.     // bad
  3.     // filename es6.js
  4.     export { es6 as default } from './AirbnbStyleGuide';

  5.     // good
  6.     // filename es6.js
  7.     import { es6 } from './AirbnbStyleGuide';
  8.     export default es6;
  9. ```

  - 10.4 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.

  1. ``` js
  2.     // bad
  3.     import foo from 'foo';
  4.     // … some other imports … //
  5.     import { named1, named2 } from 'foo';

  6.     // good
  7.     import foo, { named1, named2 } from 'foo';

  8.     // good
  9.     import foo, {
  10.       named1,
  11.       named2,
  12.     } from 'foo';
  13. ```

  - 10.5 Do not export mutable bindings.
eslint: [import/no-mutable-exports](https://github.com/benmosher/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.

  1. ``` js
  2.     // bad
  3.     let foo = 3;
  4.     export { foo };

  5.     // good
  6.     const foo = 3;
  7.     export { foo };
  8. ```

  - 10.6 In modules with a single export, prefer default export over named export.
eslint: [import/prefer-default-export](https://github.com/benmosher/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.

  1. ``` js
  2.     // bad
  3.     export function foo() {}

  4.     // good
  5.     export default function foo() {}
  6. ```

  - 10.7 Put allimports above non-import statements.
eslint: [import/first](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/first.md)
    > Why? Since imports are hoisted, keeping them all at the top prevents surprising behavior.

  1. ``` js
  2.     // bad
  3.     import foo from 'foo';
  4.     foo.init();

  5.     import bar from 'bar';

  6.     // good
  7.     import foo from 'foo';
  8.     import bar from 'bar';

  9.     foo.init();
  10. ```

  - 10.8 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.

  1. ``` js
  2.     // bad
  3.     import {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path';

  4.     // good
  5.     import {
  6.       longNameA,
  7.       longNameB,
  8.       longNameC,
  9.       longNameD,
  10.       longNameE,
  11.     } from 'path';
  12. ```

  - 10.9 Disallow Webpack loader syntax in module import statements.
eslint: [import/no-webpack-loader-syntax](https://github.com/benmosher/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.

  1. ``` js
  2.     // bad
  3.     import fooSass from 'css!sass!foo.scss';
  4.     import barCss from 'style!css!bar.css';

  5.     // good
  6.     import fooSass from 'foo.scss';
  7.     import barCss from 'bar.css';
  8. ```

  - 10.10 Do not include JavaScript filename extensions
eslint: [import/extensions](https://github.com/benmosher/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.

  1. ``` js
  2.     // bad
  3.     import foo from './foo.js';
  4.     import bar from './bar.jsx';
  5.     import baz from './baz/index.jsx';

  6.     // good
  7.     import foo from './foo';
  8.     import bar from './bar';
  9.     import baz from './baz';
  10. ```


Iterators and Generators


  - 11.1 Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops likefor-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.

  1. ``` js
  2.     const numbers = [1, 2, 3, 4, 5];

  3.     // bad
  4.     let sum = 0;
  5.     for (let num of numbers) {
  6.       sum += num;
  7.     }
  8.     sum === 15;

  9.     // good
  10.     let sum = 0;
  11.     numbers.forEach((num) => {
  12.       sum += num;
  13.     });
  14.     sum === 15;

  15.     // best (use the functional force)
  16.     const sum = numbers.reduce((total, num) => total + num, 0);
  17.     sum === 15;

  18.     // bad
  19.     const increasedByOne = [];
  20.     for (let i = 0; i < numbers.length; i++) {
  21.       increasedByOne.push(numbers[i] + 1);
  22.     }

  23.     // good
  24.     const increasedByOne = [];
  25.     numbers.forEach((num) => {
  26.       increasedByOne.push(num + 1);
  27.     });

  28.     // best (keeping it functional)
  29.     const increasedByOne = numbers.map((num) => num + 1);
  30. ```

  - 11.2 Don’t use generators for now.

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

  - 11.3 If you must use generators, or if you disregard our advice, make sure their function signature is spaced properly. eslint: [generator-star-spacing](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`.

  1. ``` js
  2.     // bad
  3.     function * foo() {
  4.       // ...
  5.     }

  6.     // bad
  7.     const bar = function * () {
  8.       // ...
  9.     };

  10.     // bad
  11.     const baz = function *() {
  12.       // ...
  13.     };

  14.     // bad
  15.     const quux = function*() {
  16.       // ...
  17.     };

  18.     // bad
  19.     function*foo() {
  20.       // ...
  21.     }

  22.     // bad
  23.     function *foo() {
  24.       // ...
  25.     }

  26.     // very bad
  27.     function
  28.     *
  29.     foo() {
  30.       // ...
  31.     }

  32.     // very bad
  33.     const wat = function
  34.     *
  35.     () {
  36.       // ...
  37.     };

  38.     // good
  39.     function* foo() {
  40.       // ...
  41.     }

  42.     // good
  43.     const foo = function* () {
  44.       // ...
  45.     };
  46. ```


Properties


  - 12.1 Use dot notation when accessing properties. eslint: [dot-notation](https://eslint.org/docs/rules/dot-notation)

  1. ``` js
  2.     const luke = {
  3.       jedi: true,
  4.       age: 28,
  5.     };

  6.     // bad
  7.     const isJedi = luke['jedi'];

  8.     // good
  9.     const isJedi = luke.jedi;
  10. ```

  - 12.2 Use bracket notation[] when accessing properties with a variable.

  1. ``` js
  2.     const luke = {
  3.       jedi: true,
  4.       age: 28,
  5.     };

  6.     function getProp(prop) {
  7.       return luke[prop];
  8.     }

  9.     const isJedi = getProp('jedi');
  10. ```

  - 12.3 Use exponentiation operator ` when calculating exponentiations. eslint: [no-restricted-properties`](https://eslint.org/docs/rules/no-restricted-properties).

  1. ``` js
  2.     // bad
  3.     const binary = Math.pow(2, 10);

  4.     // good
  5.     const binary = 2 ** 10;
  6. ```


Variables


  - 13.1 Always useconst 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)

  1. ``` js
  2.     // bad
  3.     superPower = new SuperPower();

  4.     // good
  5.     const superPower = new SuperPower();
  6. ```

  - 13.2 Use oneconst 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.

  1. ``` js
  2.     // bad
  3.     const items = getItems(),
  4.         goSportsTeam = true,
  5.         dragonball = 'z';

  6.     // bad
  7.     // (compare to above, and try to spot the mistake)
  8.     const items = getItems(),
  9.         goSportsTeam = true;
  10.         dragonball = 'z';

  11.     // good
  12.     const items = getItems();
  13.     const goSportsTeam = true;
  14.     const dragonball = 'z';
  15. ```

  - 13.3 Group all yourconsts and then group all your lets.

    > Why? This is helpful when later on you might need to assign a variable depending on one of the previously assigned variables.

  1. ``` js
  2.     // bad
  3.     let i, len, dragonball,
  4.         items = getItems(),
  5.         goSportsTeam = true;

  6.     // bad
  7.     let i;
  8.     const items = getItems();
  9.     let dragonball;
  10.     const goSportsTeam = true;
  11.     let len;

  12.     // good
  13.     const goSportsTeam = true;
  14.     const items = getItems();
  15.     let dragonball;
  16.     let i;
  17.     let length;
  18. ```

  - 13.4 Assign variables where you need them, but place them in a reasonable place.

    > Why? let and const are block scoped and not function scoped.

  1. ``` js
  2.     // bad - unnecessary function call
  3.     function checkName(hasName) {
  4.       const name = getName();

  5.       if (hasName === 'test') {
  6.         return false;
  7.       }

  8.       if (name === 'test') {
  9.         this.setName('');
  10.         return false;
  11.       }

  12.       return name;
  13.     }

  14.     // good
  15.     function checkName(hasName) {
  16.       if (hasName === 'test') {
  17.         return false;
  18.       }

  19.       const name = getName();

  20.       if (name === 'test') {
  21.         this.setName('');
  22.         return false;
  23.       }

  24.       return name;
  25.     }
  26. ```

  - 13.5 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.

  1. ``` js
  2.     // bad
  3.     (function example() {
  4.       // JavaScript interprets this as
  5.       // let a = ( b = ( c = 1 ) );
  6.       // The let keyword only applies to variable a; variables b and c become
  7.       // global variables.
  8.       let a = b = c = 1;
  9.     }());

  10.     console.log(a); // throws ReferenceError
  11.     console.log(b); // 1
  12.     console.log(c); // 1

  13.     // good
  14.     (function example() {
  15.       let a = 1;
  16.       let b = a;
  17.       let c = a;
  18.     }());

  19.     console.log(a); // throws ReferenceError
  20.     console.log(b); // throws ReferenceError
  21.     console.log(c); // throws ReferenceError

  22.     // the same applies for `const`
  23. ```

  - 13.6 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.

  1. ``` js
  2.     // bad

  3.     const array = [1, 2, 3];
  4.     let num = 1;
  5.     num++;
  6.     --num;

  7.     let sum = 0;
  8.     let truthyCount = 0;
  9.     for (let i = 0; i < array.length; i++) {
  10.       let value = array[i];
  11.       sum += value;
  12.       if (value) {
  13.         truthyCount++;
  14.       }
  15.     }

  16.     // good

  17.     const array = [1, 2, 3];
  18.     let num = 1;
  19.     num += 1;
  20.     num -= 1;

  21.     const sum = array.reduce((a, b) => a + b, 0);
  22.     const truthyCount = array.filter(Boolean).length;
  23. ```

  - 13.7 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.

  1. ``` js
  2.     // bad
  3.     const foo =
  4.       superLongLongLongLongLongLongLongLongFunctionName();

  5.     // bad
  6.     const foo
  7.       = 'superLongLongLongLongLongLongLongLongString';

  8.     // good
  9.     const foo = (
  10.       superLongLongLongLongLongLongLongLongFunctionName()
  11.     );

  12.     // good
  13.     const foo = 'superLongLongLongLongLongLongLongLongString';
  14. ```

  - 13.8 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.

  1. ``` js
  2.     // bad

  3.     const some_unused_var = 42;

  4.     // Write-only variables are not considered as used.
  5.     let y = 10;
  6.     y = 5;

  7.     // A read for a modification of itself is not considered as used.
  8.     let z = 0;
  9.     z = z + 1;

  10.     // Unused function arguments.
  11.     function getX(x, y) {
  12.         return x;
  13.     }

  14.     // good

  15.     function getXPlusY(x, y) {
  16.       return x + y;
  17.     }

  18.     const x = 1;
  19.     const y = a + 2;

  20.     alert(getXPlusY(x, y));

  21.     // 'type' is ignored even if unused because it has a rest property sibling.
  22.     // This is a form of extracting an object that omits the specified keys.
  23.     const { type, ...coords } = data;
  24.     // 'coords' is now the 'data' object without its 'type' property.
  25. ```


Hoisting


  - 14.1var declarations get hoisted to the top of their closest enclosing function scope, their assignment does not. const and let declarations are blessed with a new concept called Temporal Dead Zones (TDZ). It’s important to know why typeof is no longer safe.

  1. ``` js
  2.     // we know this wouldn’t work (assuming there
  3.     // is no notDefined global variable)
  4.     function example() {
  5.       console.log(notDefined); // => throws a ReferenceError
  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.     // the interpreter is hoisting the variable
  16.     // declaration to the top of the scope,
  17.     // which means our example could be rewritten as:
  18.     function example() {
  19.       let declaredButNotAssigned;
  20.       console.log(declaredButNotAssigned); // => undefined
  21.       declaredButNotAssigned = true;
  22.     }

  23.     // using const and let
  24.     function example() {
  25.       console.log(declaredButNotAssigned); // => throws a ReferenceError
  26.       console.log(typeof declaredButNotAssigned); // => throws a ReferenceError
  27.       const declaredButNotAssigned = true;
  28.     }
  29. ```

  - 14.2 Anonymous function expressions hoist their variable name, but not the function assignment.

  1. ``` js
  2.     function example() {
  3.       console.log(anonymous); // => undefined

  4.       anonymous(); // => TypeError anonymous is not a function

  5.       var anonymous = function () {
  6.         console.log('anonymous function expression');
  7.       };
  8.     }
  9. ```

  - 14.3 Named function expressions hoist the variable name, not the function name or the function body.

  1. ``` js
  2.     function example() {
  3.       console.log(named); // => undefined

  4.       named(); // => TypeError named is not a function

  5.       superPower(); // => ReferenceError superPower is not defined

  6.       var named = function superPower() {
  7.         console.log('Flying');
  8.       };
  9.     }

  10.     // the same is true when the function name
  11.     // is the same as the variable name.
  12.     function example() {
  13.       console.log(named); // => undefined

  14.       named(); // => TypeError named is not a function

  15.       var named = function named() {
  16.         console.log('named');
  17.       };
  18.     }
  19. ```

  - 14.4 Function declarations hoist their name and the function body.

  1. ``` js
  2.     function example() {
  3.       superPower(); // => Flying

  4.       function superPower() {
  5.         console.log('Flying');
  6.       }
  7.     }
  8. ```

  - For more information refer to JavaScript Scoping & Hoisting by Ben Cherry.


Comparison Operators & Equality


  - 15.1 Use=== and !== over == and !=. eslint: [eqeqeq](https://eslint.org/docs/rules/eqeqeq)

  - 15.2 Conditional statements such as theif 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

  1. ``` js
  2.     if ([0] && []) {
  3.       // true
  4.       // an array (even an empty one) is an object, objects will evaluate to true
  5.     }
  6. ```

  - 15.3 Use shortcuts for booleans, but explicit comparisons for strings and numbers.

  1. ``` js
  2.     // bad
  3.     if (isValid === true) {
  4.       // ...
  5.     }

  6.     // good
  7.     if (isValid) {
  8.       // ...
  9.     }

  10.     // bad
  11.     if (name) {
  12.       // ...
  13.     }

  14.     // good
  15.     if (name !== '') {
  16.       // ...
  17.     }

  18.     // bad
  19.     if (collection.length) {
  20.       // ...
  21.     }

  22.     // good
  23.     if (collection.length > 0) {
  24.       // ...
  25.     }
  26. ```

  - 15.4 For more information see Truth Equality and JavaScript by Angus Croll.

  - 15.5 Use braces to create blocks incase 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 thin