@17media/eslint-config-17media 中文文档教程

发布于 4年前 浏览 23 项目主页 更新于 3年前

17 Media JavaScript Style Guide

一个最合理的 JavaScript 方法

这是 airbnb/javascript 的一个分支

Installation / ESLint setup

npm install --save-dev @17media/eslint-config-17media
echo '{ "extends": "@17media/eslint-config-17media/browser" }' > .eslintrc

/browser/node 用于不同的环境。

Other Style Guides

Table of Contents

  1. Types
  2. References
  3. Objects
  4. Arrays
  5. Destructuring
  6. Strings
  7. Functions
  8. Arrow Functions
  9. Classes & Constructors
  10. Modules
  11. Iterators and Generators
  12. Properties
  13. Variables
  14. Hoisting
  15. Comparison Operators & Equality
  16. Blocks
  17. Comments
  18. Whitespace
  19. Commas
  20. Semicolons
  21. Type Casting & Coercion
  22. Naming Conventions
  23. Accessors
  24. Events
  25. jQuery
  26. ECMAScript 5 Compatibility
  27. ECMAScript 6+ (ES 2015+) Styles
  28. Testing
  29. Performance
  30. Resources

Types

  • 1.1 基元:当你访问一个原始类型时,你直接在它的值上工作。

    • string
    • number
    • boolean
    • null
    • undefined
    const foo = 1;
    let bar = foo;
    
    bar = 9;
    
    console.log(foo, bar); // => 1, 9
    

  • 1.2 复杂:当您访问复杂类型时,您将处理对其值的引用。

    • object
    • array
    • function
    const foo = [1, 2];
    const bar = foo;
    
    bar[0] = 9;
    
    console.log(foo[0], bar[0]); // => 9, 9
    

⬆ 返回顶部

References

  • 2.1 对所有引用使用const; 避免使用 var。 eslint:prefer-constno-const-assign

    为什么? 这确保您不能重新分配您的引用,这可能会导致错误和难以理解的代码。

    // bad
    var a = 1;
    var b = 2;
    
    // good
    const a = 1;
    const b = 2;
    

  • 2.2 如果你必须重新分配引用,使用 let 而不是 var。 eslint:no-var jscs:disallowVar

    为什么? let 是块范围的,而不是像 var 那样的函数范围的。

    // bad
    var count = 1;
    if (true) {
      count += 1;
    }
    
    // good, use the let.
    let count = 1;
    if (true) {
      count += 1;
    }
    

  • 2.3 请注意letconst 都是块作用域的。

    // const and let only exist in the blocks they are defined in.
    {
      let a = 1;
      const b = 1;
    }
    console.log(a); // ReferenceError
    console.log(b); // ReferenceError
    

⬆ 返回顶部

Objects

  • 3.1 使用文字语法创建对象。 eslint:no-new-object

    // bad
    const item = new Object();
    
    // good
    const item = {};
    

  • 3.2 创建具有动态属性的对象时使用计算属性名称名字。

    为什么? 它们允许您在一个地方定义一个对象的所有属性。

    function getKey(k) {
      return `a key named ${k}`;
    }
    
    // bad
    const obj = {
      id: 5,
      name: 'San Francisco',
    };
    obj[getKey('enabled')] = true;
    
    // good
    const obj = {
      id: 5,
      name: 'San Francisco',
      [getKey('enabled')]: true,
    };
    

  • 3.3 使用对象方法简写. eslint:object-shorthand jscs:requireEnhancedObjectLiterals

    // bad
    const atom = {
      value: 1,
    
      addValue: function (value) {
        return atom.value + value;
      },
    };
    
    // good
    const atom = {
      value: 1,
    
      addValue(value) {
        return atom.value + value;
      },
    };
    

  • 3.4 使用属性值简写。 eslint:object-shorthand jscs:requireEnhancedObjectLiterals

    为什么? 书写和描述性较短。

    const lukeSkywalker = 'Luke Skywalker';
    
    // bad
    const obj = {
      lukeSkywalker: lukeSkywalker,
    };
    
    // good
    const obj = {
      lukeSkywalker,
    };
    

  • 3.6 仅引用作为无效标识符的属性。 eslint:quote-props jscs:disallowQuotedKeysInObjects

    为什么? 一般来说,我们认为它在主观上更容易阅读。 它改进了语法高亮,也更容易被许多 JS 引擎优化。

    // bad
    const bad = {
      'foo': 3,
      'bar': 4,
      'data-blah': 5,
    };
    
    // good
    const good = {
      foo: 3,
      bar: 4,
      'data-blah': 5,
    };
    

  • 3.7 不要调用Object.prototype方法直接,例如 hasOwnPropertypropertyIsEnumerableisPrototypeOf

    为什么? 这些方法可能被相关对象的属性所掩盖 - 考虑 { hasOwnProperty: false } - 或者,对象可能是空对象 (Object.create(null) ).

    // bad
    console.log(object.hasOwnProperty(key));
    
    // good
    console.log(Object.prototype.hasOwnProperty.call(object, key));
    
    // best
    const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
    /* or */
    import has from 'has';
    // ...
    console.log(has.call(object, key));
    

  • 3.8Object.assign 浅拷贝对象。 使用对象剩余运算符来获取省略了某些属性的新对象。

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

⬆ 返回顶部

Arrays

  • 4.1 使用文字语法创建数组。 eslint:no-array-constructor

    // bad
    const items = new Array();
    
    // good
    const items = [];
    

  • 4.2 使用 Array#push 而不是直接分配以将项目添加到数组。

    const someStack = [];
    
    // bad
    someStack[someStack.length] = 'abracadabra';
    
    // good
    someStack.push('abracadabra');
    

  • 4.3 使用数组展开< code>... 复制数组。

    // bad
    const len = items.length;
    const itemsCopy = [];
    let i;
    
    for (i = 0; i < len; i += 1) {
      itemsCopy[i] = items[i];
    }
    
    // good
    const itemsCopy = [...items];
    

  • 4.4 转换一个类数组对象到数组,使用 Array.from

    const foo = document.querySelectorAll('.foo');
    const nodes = Array.from(foo);
    

  • 4.5 使用返回数组方法回调中的语句。 如果函数体由 8.2 之后的单个语句组成,则可以省略 return。 eslint:array-callback-return

    // good
    [1, 2, 3].map((x) => {
      const y = x + 1;
      return x * y;
    });
    
    // good
    [1, 2, 3].map(x => x + 1);
    
    // bad
    const flat = {};
    [[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
      const flatten = memo.concat(item);
      flat[index] = flatten;
    });
    
    // good
    const flat = {};
    [[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
      const flatten = memo.concat(item);
      flat[index] = flatten;
      return flatten;
    });
    
    // bad
    inbox.filter((msg) => {
      const { subject, author } = msg;
      if (subject === 'Mockingbird') {
        return author === 'Harper Lee';
      } else {
        return false;
      }
    });
    
    // good
    inbox.filter((msg) => {
      const { subject, author } = msg;
      if (subject === 'Mockingbird') {
        return author === 'Harper Lee';
      }
    
      return false;
    });
    

⬆ 回到顶部

  • 4.6 Use line breaks after open and before close array brackets if an array has multiple lines
  // bad
  const arr = [
    [0, 1], [2, 3], [4, 5],
  ];

  const objectInArray = [{
    id: 1,
  }, {
    id: 2,
  }];

  const numberInArray = [
    1, 2,
  ];

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

  const objectInArray = [
    {
      id: 1,
    },
    {
      id: 2,
    },
  ];

  const numberInArray = [
    1,
    2,
  ];

⬆ 返回顶部

Destructuring

  • 5.1 在访问和使用对象的多个属性时使用对象解构。 jscs:requireObjectDestructuring

    为什么? 解构使您免于为这些属性创建临时引用。

    // bad
    function getFullName(user) {
      const firstName = user.firstName;
      const lastName = user.lastName;
    
      return `${firstName} ${lastName}`;
    }
    
    // good
    function getFullName(user) {
      const { firstName, lastName } = user;
      return `${firstName} ${lastName}`;
    }
    
    // good
    function getFullName({ firstName, lastName }) {
      return `${firstName} ${lastName}`;
    }
    

  • 5.2 使用数组解构。 jscs:requireArrayDestructuring

    const arr = [1, 2, 3, 4];
    
    // bad
    const first = arr[0];
    const second = arr[1];
    
    // good
    const [first, second] = arr;
    

  • 5.3 对多个返回值使用对象解构,而不是数组解构。 jscs:disallowArrayDestructuringReturn

    为什么? 您可以随着时间的推移添加新属性或更改事物的顺序而不会中断调用站点。

    // bad
    function processInput(input) {
      // then a miracle occurs
      return [left, right, top, bottom];
    }
    
    // the caller needs to think about the order of return data
    const [left, __, top] = processInput(input);
    
    // good
    function processInput(input) {
      // then a miracle occurs
      return { left, right, top, bottom };
    }
    
    // the caller selects only the data they need
    const { left, top } = processInput(input);
    

⬆ 返回顶部

Strings

  • 6.1 对字符串使用单引号''。 eslint:quotes jscs:validateQuoteMarks

    // bad
    const name = "Capt. Janeway";
    
    // bad - template literals should contain interpolation or newlines
    const name = `Capt. Janeway`;
    
    // good
    const name = 'Capt. Janeway';
    

  • 6.2 导致行超过 100 个字符的字符串不应使用字符串连接跨多行编写。

    为什么? 损坏的字符串使用起来很痛苦,并且使代码更难搜索。

    // bad
    const errorMessage = 'This is a super long error that was thrown because \
    of Batman. When you stop to think about how Batman had anything to do \
    with this, you would get nowhere \
    fast.';
    
    // bad
    const errorMessage = 'This is a super long error that was thrown because ' +
      'of Batman. When you stop to think about how Batman had anything to do ' +
      'with this, you would get nowhere fast.';
    
    // good
    const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
    

  • 6.3 以编程方式构建时字符串,使用模板字符串而不是连接。 eslint:prefer-template template-curly-spacing jscs: requireTemplateStrings

    为什么? 模板字符串为您提供可读、简洁的语法以及适当的换行符和字符串插值功能。

    // bad
    function sayHi(name) {
      return 'How are you, ' + name + '?';
    }
    
    // bad
    function sayHi(name) {
      return ['How are you, ', name, '?'].join();
    }
    
    // bad
    function sayHi(name) {
      return `How are you, ${ name }?`;
    }
    
    // good
    function sayHi(name) {
      return `How are you, ${name}?`;
    }
    

  • 6.4 永远不要使用 eval () 在一个字符串上,它打开了太多的漏洞。

  • 6.5 不要对字符串中的字符进行不必要的转义。 eslint:no-useless-escape

    为什么? 反斜杠会损害可读性,因此它们应该只在必要时出现。

    // bad
    const foo = '\'this\' \i\s \"quoted\"';
    
    // good
    const foo = '\'this\' is "quoted"';
    const foo = `my name is '${name}'`;
    

⬆ 返回顶部

Functions

  • 7.1 使用命名函数表达式而不是函数声明。 eslint:func-style jscs:disallowFunctionDeclarations

    为什么? 函数声明被提升,这意味着很容易——太容易了——在文件中定义函数之前引用它。 这会损害可读性和可维护性。 如果您发现某个函数的定义太大或太复杂以至于影响了对文件其余部分的理解,那么也许是时候将它提取到自己的模块中了! 不要忘记为表达式命名 - 匿名函数会使在错误的调用堆栈中定位问题变得更加困难。 (讨论

    // bad
    const foo = function () {
      // ...
    };
    
    // okay
    function foo() {
      // ...
    }
    
    // good
    const foo = function bar() {
      // ...
    };
    

  • 7.2 将立即调用的函数表达式括在括号中。 eslint:wrap-iife jscs:requireParenthesesAroundIIFE

    为什么? 一个立即调用的函数表达式是一个单一的单元——将它和它的调用括号一起包装在括号中,清楚地表达了这一点。 请注意,在一个到处都是模块的世界中,您几乎不需要 IIFE。

    // immediately-invoked function expression (IIFE)
    (function () {
      console.log('Welcome to the Internet. Please follow me.');
    }());
    

  • 7.3 从不声明非功能块中的功能(if、while 等)。 而是将函数分配给变量。 浏览器将允许您这样做,但它们对它的解释都不同,这是个坏消息。 eslint:no-loop-func

  • 7.4 注意: ECMA-262 将 定义为语句列表。 函数声明不是语句。 阅读 ECMA-262 关于这个问题的说明

    // bad
    if (currentUser) {
      function test() {
        console.log('Nope.');
      }
    }
    
    // good
    let test;
    if (currentUser) {
      test = () => {
        console.log('Yup.');
      };
    }
    

  • 7.5 从不命名一个参数 arguments。 这将优先于赋予每个函数范围的 arguments 对象。

    // bad
    function foo(name, options, arguments) {
      // ...
    }
    
    // good
    function foo(name, options, args) {
      // ...
    }
    

  • 7.6 永远不要使用参数,选择使用 rest 语法 ... 代替。 eslint:prefer-rest-params

    为什么? ... 明确说明您要提取哪些参数。 另外,剩余参数是一个真正的数组,而不仅仅是类似数组的 arguments

    // bad
    function concatenateAll() {
      const args = Array.prototype.slice.call(arguments);
      return args.join('');
    }
    
    // good
    function concatenateAll(...args) {
      return args.join('');
    }
    

  • 7.7 使用默认参数语法而不是改变函数参数。

    // really bad
    function handleThings(opts) {
      // No! We shouldn't mutate function arguments.
      // Double bad: if opts is falsy it'll be set to an object which may
      // be what you want but it can introduce subtle bugs.
      opts = opts || {};
      // ...
    }
    
    // still bad
    function handleThings(opts) {
      if (opts === void 0) {
        opts = {};
      }
      // ...
    }
    
    // good
    function handleThings(opts = {}) {
      // ...
    }
    

  • 7.8 使用默认参数避免副作用。

    为什么? 他们很难推理。

    var b = 1;
    // bad
    function count(a = b++) {
      console.log(a);
    }
    count();  // 1
    count();  // 2
    count(3); // 3
    count();  // 3
    

  • 7.9 总是放默认参数最后。

    // bad
    function handleThings(opts = {}, name) {
      // ...
    }
    
    // good
    function handleThings(name, opts = {}) {
      // ...
    }
    

  • 7.10 永远不要使用 Function 构造函数来创建一个新函数。 eslint:no-new-func

    为什么? 以这种方式创建一个函数会评估一个类似于 eval() 的字符串,这会打开漏洞。

    // bad
    var add = new Function('a', 'b', 'return a + b');
    
    // still bad
    var subtract = Function('a', 'b', 'return a - b');
    

  • 7.11 间距一个函数签名。 eslint:space-before-function-paren space-before-blocks

    为什么? 一致性很好,在添加或删除名称时不必添加或删除空格。

    // bad
    const f = function(){};
    const g = function (){};
    const h = function() {};
    
    // good
    const x = function () {};
    const y = function a() {};
    

  • 7.12 从不改变参数。 eslint:no-param-reassign

    为什么? 操作作为参数传入的对象可能会在原始调用者中产生不需要的变量副作用。

    // bad
    function f1(obj) {
      obj.key = 1;
    }
    
    // good
    function f2(obj) {
      const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;
    }
    

  • 7.13 从不重新分配参数。 eslint:no-param-reassign

    为什么? 重新分配参数可能会导致意外行为,尤其是在访问 arguments 对象时。 它还可能导致优化问题,尤其是在 V8 中。

    // bad
    function f1(a) {
      a = 1;
      // ...
    }
    
    function f2(a) {
      if (!a) { a = 1; }
      // ...
    }
    
    // good
    function f3(a) {
      const b = a || 1;
      // ...
    }
    
    function f4(a = 1) {
      // ...
    }
    

  • 7.14 更喜欢使用扩展运算符 ... 来调用可变参数函数。 eslint:prefer-spread

    为什么? 它更干净,您不需要提供上下文,并且您不能轻松地将 newapply 组合在一起。

    // bad
    const x = [1, 2, 3, 4, 5];
    console.log.apply(console, x);
    
    // good
    const x = [1, 2, 3, 4, 5];
    console.log(...x);
    
    // bad
    new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));
    
    // good
    new Date(...[2016, 8, 5]);
    

  • 7.15 具有多行签名或调用的函数应该是缩进就像本指南中的所有其他多行列表一样:每个项目单独一行,最后一个项目有尾随逗号。

    // bad
    function foo(bar,
                 baz,
                 quux) {
      // ...
    }
    
    // good
    function foo(
      bar,
      baz,
      quux,
    ) {
      // ...
    }
    
    // bad
    console.log(foo,
      bar,
      baz);
    
    // good
    console.log(
      foo,
      bar,
      baz,
    );
    

⬆ 返回顶部

Arrow Functions

  • 8.1 当必须使用函数表达式时(如传递匿名函数时),请使用箭头函数表示法。 eslint:prefer-arrow-callback, arrow-spacing jscs:requireArrowFunctions

    为什么? 它创建一个在 this 上下文中执行的函数版本,这通常是您想要的,并且是一种更简洁的语法。

    为什么不? 如果您有一个相当复杂的函数,您可以将该逻辑移出到它自己的函数声明中。

    // bad
    [1, 2, 3].map(function (x) {
      const y = x + 1;
      return x * y;
    });
    
    // good
    [1, 2, 3].map((x) => {
      const y = x + 1;
      return x * y;
    });
    

  • 8.2 如果函数体由单个表达式组成,省略大括号并使用隐式返回。 否则,保留大括号并使用 return 语句。 eslint:arrow-parensarrow-body-style jscs:disallowParenthesesAroundArrowParam, requireShorthandArrowFunctions

    为什么? 语法糖。 当多个函数链接在一起时,它读起来很好。

    // bad
    [1, 2, 3].map(number => {
      const nextNumber = number + 1;
      `A string containing the ${nextNumber}.`;
    });
    
    // good
    [1, 2, 3].map(number => `A string containing the ${number}.`);
    
    // good
    [1, 2, 3].map((number) => {
      const nextNumber = number + 1;
      return `A string containing the ${nextNumber}.`;
    });
    
    // good
    [1, 2, 3].map((number, index) => ({
      [index]: number,
    }));
    

  • 8.3 万一表达式跨越多行,将其括在括号中以提高可读性。

    为什么? 它清楚地显示了函数的开始和结束位置。

    // bad
    ['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call(
        httpMagicObjectWithAVeryLongName,
        httpMethod,
      )
    );
    
    // good
    ['get', 'post', 'put'].map(httpMethod => (
      Object.prototype.hasOwnProperty.call(
        httpMagicObjectWithAVeryLongName,
        httpMethod,
      )
    ));
    

  • 8.4 如果你的函数只有一个参数并且不使用大括号,则省略括号。 否则,为了清晰和一致,始终在参数周围加上括号。 注意:始终使用括号也是可以接受的,在这种情况下,请为 eslint 使用 "always" 选项或不为 jsc 包含 disallowParenthesesAroundArrowParam。 eslint:arrow-parens jscs:disallowParenthesesAroundArrowParam

    为什么? 减少视觉混乱。

    // bad
    [1, 2, 3].map((x) => x * x);
    
    // good
    [1, 2, 3].map(x => x * x);
    
    // good
    [1, 2, 3].map(number => (
      `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`
    ));
    
    // bad
    [1, 2, 3].map(x => {
      const y = x + 1;
      return x * y;
    });
    
    // good
    [1, 2, 3].map((x) => {
      const y = x + 1;
      return x * y;
    });
    

  • 8.5 避免混淆箭头函数语法 ( =>) 与比较运算符 (<=, >=)。 eslint:no-confusing-arrow

    // bad
    const itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize;
    
    // bad
    const itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize;
    
    // good
    const itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize);
    
    // good
    const itemHeight = (item) => {
      const { height, largeSize, smallSize } = item;
      return height > 256 ? largeSize : smallSize;
    };
    

⬆ 回到顶部

Classes & Constructors

  • < a href="#constructors--use-class">9.1 始终使用 class。 避免直接操作 prototype

    为什么? class 语法更简洁,更容易推理。

    // bad
    function Queue(contents = []) {
      this.queue = [...contents];
    }
    Queue.prototype.pop = function () {
      const value = this.queue[0];
      this.queue.splice(0, 1);
      return value;
    };
    
    
    // good
    class Queue {
      constructor(contents = []) {
        this.queue = [...contents];
      }
      pop() {
        const value = this.queue[0];
        this.queue.splice(0, 1);
        return value;
      }
    }
    

  • 9.2 使用extends< /code> 用于继承。

    为什么? 它是一种在不破坏 instanceof 的情况下继承原型功能的内置方法。

    // bad
    const inherits = require('inherits');
    function PeekableQueue(contents) {
      Queue.apply(this, contents);
    }
    inherits(PeekableQueue, Queue);
    PeekableQueue.prototype.peek = function () {
      return this.queue[0];
    };
    
    // good
    class PeekableQueue extends Queue {
      peek() {
        return this.queue[0];
      }
    }
    

  • 9.3 方法可以返回this 以帮助进行方法链接。

    // bad
    Jedi.prototype.jump = function () {
      this.jumping = true;
      return true;
    };
    
    Jedi.prototype.setHeight = function (height) {
      this.height = height;
    };
    
    const luke = new Jedi();
    luke.jump(); // => true
    luke.setHeight(20); // => undefined
    
    // good
    class Jedi {
      jump() {
        this.jumping = true;
        return this;
      }
    
      setHeight(height) {
        this.height = height;
        return this;
      }
    }
    
    const luke = new Jedi();
    
    luke.jump()
      .setHeight(20);
    

  • 9.4 写个自定义的就可以了toString() 方法,只需确保它成功运行并且不会产生副作用。

    class Jedi {
      constructor(options = {}) {
        this.name = options.name || 'no name';
      }
    
      getName() {
        return this.name;
      }
    
      toString() {
        return `Jedi - ${this.getName()}`;
      }
    }
    

  • 9.5 类有如果未指定,则为默认构造函数。 空构造函数或仅委托给父类的构造函数是不必要的。 eslint:no-useless-constructor

    // bad
    class Jedi {
      constructor() {}
    
      getName() {
        return this.name;
      }
    }
    
    // bad
    class Rey extends Jedi {
      constructor(...args) {
        super(...args);
      }
    }
    
    // good
    class Rey extends Jedi {
      constructor(...args) {
        super(...args);
        this.name = 'Rey';
      }
    }
    

  • 9.6 避免重复的类成员。 eslint:no-dupe-class-members

    为什么? 重复的类成员声明会默默地选择最后一个 - 重复几乎肯定是一个错误。

    // bad
    class Foo {
      bar() { return 1; }
      bar() { return 2; }
    }
    
    // good
    class Foo {
      bar() { return 1; }
    }
    
    // good
    class Foo {
      bar() { return 2; }
    }
    

⬆ 返回顶部

Modules

  • 10.1 始终使用模块(import/export)非标准模块系统。 您始终可以转换为您喜欢的模块系统。

    为什么? 模块是未来,让我们现在就开始使用未来吧。

    // bad
    const AirbnbStyleGuide = require('./AirbnbStyleGuide');
    module.exports = AirbnbStyleGuide.es6;
    
    // ok
    import AirbnbStyleGuide from './AirbnbStyleGuide';
    export default AirbnbStyleGuide.es6;
    
    // best
    import { es6 } from './AirbnbStyleGuide';
    export default es6;
    

  • 10.4 仅从一处路径导入。 eslint:no-duplicate-imports

    为什么? 从同一路径导入多行代码会使代码更难维护。

    // bad
    import foo from 'foo';
    // … some other imports … //
    import { named1, named2 } from 'foo';
    
    // good
    import foo, { named1, named2 } from 'foo';
    
    // good
    import foo, {
      named1,
      named2,
    } from 'foo';
    

  • 10.5 不要导出可变绑定。 eslint:import/no-mutable-exports

    为什么? 通常应避免突变,但在导出可变绑定时尤其如此。 虽然某些特殊情况可能需要这种技术,但一般来说,只应导出常量引用。

    // bad
    let foo = 3;
    export { foo };
    
    // good
    const foo = 3;
    export { foo };
    

  • 10.7 将所有 import 置于非导入语句。 eslint:import/first

    为什么? 由于 import 被提升,将它们全部放在顶部可以防止意外行为。

    // bad
    import foo from 'foo';
    foo.init();
    
    import bar from 'bar';
    
    // good
    import foo from 'foo';
    import bar from 'bar';
    
    foo.init();
    

  • 10.8 多行导入应该只缩进像多行数组和对象字面量。

    为什么? 花括号遵循与风格指南中所有其他花括号块相同的缩进规则,尾随逗号也是如此。

    // bad
    import {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path';
    
    // good
    import {
      longNameA,
      longNameB,
      longNameC,
      longNameD,
      longNameE,
    } from 'path';
    

  • 10.8 绝对导入先于相对导入。 eslint:import/first

    // bad
    import Component from './Component';
    import _ from 'lodash';
    
    // good
    import _ from 'lodash';
    import Component from './Component';
    

  • 10.8 在导入语句后插入一个新行。 eslint:import/newline-after-import

    // bad
    import _ from 'lodash';
    import Component from './Component';
    const a = 5;
    
    // good
    import _ from 'lodash';
    import Component from './Component';
    
    const a = 5;
    

⬆返回顶部

Iterators and Generators

  • 11.1 不要使用迭代器。 首选 JavaScript 的高阶函数,而不是像 for-infor-of 这样的循环。 eslint:no-iterator no-restricted-syntax

    为什么? 这强制执行了我们不变的规则。 处理返回值的纯函数比处理副作用更容易推理。

    使用 map() / every() / filter() / find() / findIndex( ) / reduce() / some() / ... 遍历数组,以及 Object.keys() / Object.values() / Object.entries() 生成数组,以便您可以迭代对象。

    const numbers = [1, 2, 3, 4, 5];
    
    // bad
    let sum = 0;
    for (let num of numbers) {
      sum += num;
    }
    sum === 15;
    
    // good
    let sum = 0;
    numbers.forEach(num => sum += num);
    sum === 15;
    
    // best (use the functional force)
    const sum = numbers.reduce((total, num) => total + num, 0);
    sum === 15;
    
    // bad
    const increasedByOne = [];
    for (let i = 0; i < numbers.length; i++) {
      increasedByOne.push(numbers[i] + 1);
    }
    
    // good
    const increasedByOne = [];
    numbers.forEach(num => increasedByOne.push(num + 1));
    
    // best (keeping it functional)
    const increasedByOne = numbers.map(num => num + 1);
    

  • 11.2 不要将生成器用于现在。 除非需要库(例如 redux-saga)。

    为什么? 它们不能很好地转换为 ES5。

  • 11.3 如果你必须使用生成器,或者你忽略 我们的建议,确保它们的函数签名间隔正确。 eslint:generator-star-spacing

    为什么? function* 是同一概念关键字的一部分 - * 不是 function 的修饰符,function* 是一个独特的结构,不同于function

    // bad
    function * foo() {
      // ...
    }
    
    // bad
    const bar = function * () {
      // ...
    };
    
    // bad
    const baz = function *() {
      // ...
    };
    
    // bad
    const quux = function*() {
      // ...
    };
    
    // bad
    function*foo() {
      // ...
    }
    
    // bad
    function *foo() {
      // ...
    }
    
    // very bad
    function
    *
    foo() {
      // ...
    }
    
    // very bad
    const wat = function
    *
    () {
      // ...
    };
    
    // good
    function* foo() {
      // ...
    }
    
    // good
    const foo = function* () {
      // ...
    };
    

⬆ 返回顶部

Properties

  • 12.1 访问属性时使用点符号。 eslint:dot-notation jscs:requireDotNotation

    const luke = {
      jedi: true,
      age: 28,
    };
    
    // bad
    const isJedi = luke['jedi'];
    
    // good
    const isJedi = luke.jedi;
    

  • < a href="#properties--bracket">12.2 使用变量访问属性时使用括号表示法 []

    const luke = {
      jedi: true,
      age: 28,
    };
    
    function getProp(prop) {
      return luke[prop];
    }
    
    const isJedi = getProp('jedi');
    

⬆ 返回顶部

Variables

  • 13.1 始终使用constlet 来声明变量。 不这样做会导致全局变量。 我们希望避免污染全局命名空间。 星球队长警告过我们这一点。 eslint:no-undef prefer-const

    // bad
    superPower = new SuperPower();
    
    // good
    const superPower = new SuperPower();
    

    < /a>

  • 13.2 每个变量使用一个 constlet 声明。 eslint:one-var jscs:disallowMultipleVarDecl

    为什么? 以这种方式添加新的变量声明更容易,而且您永远不必担心将 ; 换成 , 或引入仅标点符号的差异。 您还可以使用调试器单步执行每个声明,而不是一次跳过所有声明。

    // bad
    const items = getItems(),
        goSportsTeam = true,
        dragonball = 'z';
    
    // bad
    // (compare to above, and try to spot the mistake)
    const items = getItems(),
        goSportsTeam = true;
        dragonball = 'z';
    
    // good
    const items = getItems();
    const goSportsTeam = true;
    const dragonball = 'z';
    

  • 13.3 将所有的 const 分组,然后将所有的 let 分组。

    为什么? 这在稍后您可能需要根据先前分配的变量之一分配变量时很有用。

    // bad
    let i, len, dragonball,
        items = getItems(),
        goSportsTeam = true;
    
    // bad
    let i;
    const items = getItems();
    let dragonball;
    const goSportsTeam = true;
    let len;
    
    // good
    const goSportsTeam = true;
    const items = getItems();
    let dragonball;
    let i;
    let length;
    

  • 13.4 在需要的地方赋值变量,但是要放在合理的地方。

    为什么? letconst 是块作用域而不是函数作用域。

    // bad - unnecessary function call
    function checkName(hasName) {
      const name = getName();
    
      if (hasName === 'test') {
        return false;
      }
    
      if (name === 'test') {
        this.setName('');
        return false;
      }
    
      return name;
    }
    
    // good
    function checkName(hasName) {
      if (hasName === 'test') {
        return false;
      }
    
      const name = getName();
    
      if (name === 'test') {
        this.setName('');
        return false;
      }
    
      return name;
    }
    

  • 13.5 不要链接变量赋值。

    为什么? 链接变量赋值创建隐式全局变量。

    // bad
    (function example() {
      // JavaScript interprets this as
      // let a = ( b = ( c = 1 ) );
      // The let keyword only applies to variable a; variables b and c become
      // global variables.
      let a = b = c = 1;
    }());
    
    console.log(a); // undefined
    console.log(b); // 1
    console.log(c); // 1
    
    // good
    (function example() {
      let a = 1;
      let b = a;
      let c = a;
    }());
    
    console.log(a); // undefined
    console.log(b); // undefined
    console.log(c); // undefined
    
    // the same applies for `const`
    

  • 13.6 避免使用一元递增和递减 (++, --)。 在 for-loop 中使用它对于一般实践来说是可以接受的(尽管你也应该避免使用 for-loop)。 eslint:no-plusplus

    为什么? 根据 eslint 文档,一元递增和递减语句会自动插入分号,并可能导致在应用程序中递增或递减值时出现静默错误。 使用像 num += 1 而不是 num++num ++ 这样的语句来改变你的值也更具表现力。 不允许一元递增和递减语句还可以防止您无意中预递增/预递减值,这也可能导致程序出现意外行为。

    // bad
    const array = [1, 2, 3];
    let num = 1;
    num++;
    --num;
    
    // okay
    for (let i = 0; i < 10; i++) {
      console.log(i);
    }
    // better
    for (let i = 0; i < 10; i += 1) {
      console.log(i);
    }
    
    // good
    const array = [1, 2, 3];
    let num = 1;
    num += 1;
    num -= 1;
    
    const sum = array.reduce((a, b) => a + b, 0);
    const truthyCount = array.filter(Boolean).length;
    

⬆ 回到顶部

Hoisting

  • 14.1 var 声明被提升到它们作用域的顶部,它们的赋值没有。 constlet 声明被称为 时间死区 (TDZ)。 了解为什么 typeof 不再安全 很重要。

    // we know this wouldn't work (assuming there
    // is no notDefined global variable)
    function example() {
      console.log(notDefined); // => throws a ReferenceError
    }
    
    // creating a variable declaration after you
    // reference the variable will work due to
    // variable hoisting. Note: the assignment
    // value of `true` is not hoisted.
    function example() {
      console.log(declaredButNotAssigned); // => undefined
      var declaredButNotAssigned = true;
    }
    
    // the interpreter is hoisting the variable
    // declaration to the top of the scope,
    // which means our example could be rewritten as:
    function example() {
      let declaredButNotAssigned;
      console.log(declaredButNotAssigned); // => undefined
      declaredButNotAssigned = true;
    }
    
    // using const and let
    function example() {
      console.log(declaredButNotAssigned); // => throws a ReferenceError
      console.log(typeof declaredButNotAssigned); // => throws a ReferenceError
      const declaredButNotAssigned = true;
    }
    

  • 14.2 匿名函数表达式会提升它们的变量名,但不会提升函数赋值。

    function example() {
      console.log(anonymous); // => undefined
    
      anonymous(); // => TypeError anonymous is not a function
    
      var anonymous = function () {
        console.log('anonymous function expression');
      };
    }
    

  • 14.3 命名函数表达式提升变量名,而不是函数名或函数体。

    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      superPower(); // => ReferenceError superPower is not defined
    
      var named = function superPower() {
        console.log('Flying');
      };
    }
    
    // the same is true when the function name
    // is the same as the variable name.
    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      var named = function named() {
        console.log('named');
      };
    }
    

  • 14.4 函数声明提升他们的名字和函数体。

    function example() {
      superPower(); // => Flying
    
      function superPower() {
        console.log('Flying');
      }
    }
    
  • 有关详细信息,请参阅 JavaScript 作用域与提升 Ben Cherry 吊装。

⬆ 返回顶部

Comparison Operators & Equality

  • 15.1== 上使用 ===!==!=。 eslint:eqeqeq

  • 15.2 条件语句,例如 if 语句使用强制转换来计算它们的表达式ToBoolean 抽象方法并始终遵循以下简单规则:

    • 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
    if ([0] && []) {
      // true
      // an array (even an empty one) is an object, objects will evaluate to true
    }
    

  • 15.3 对布尔值使用快捷方式,但对字符串和数字使用显式比较。

    // bad
    if (isValid === true) {
      // ...
    }
    
    // good
    if (isValid) {
      // ...
    }
    
    // bad
    if (name) {
      // ...
    }
    
    // good
    if (name !== '') {
      // ...
    }
    
    // bad
    if (collection.length) {
      // ...
    }
    
    // good
    if (collection.length > 0) {
      // ...
    }
    

  • 15.4 有关详细信息,请参阅 Angus Croll 的真相平等和 JavaScript

  • 15.5 使用大括号在包含词法声明的 casedefault 子句中创建块(例如 letconstfunction)。

    为什么? 词法声明在整个 switch 块中可见,但仅在分配时才初始化,这仅在达到其 case 时发生。 当多个 case 子句试图定义同一事物时,这会导致问题。

    eslint 规则:no-case-declarations

    // bad
    switch (foo) {
      case 1:
        let x = 1;
        break;
      case 2:
        const y = 2;
        break;
      case 3:
        function f() {
          // ...
        }
        break;
      default:
        class C {}
    }
    
    // good
    switch (foo) {
      case 1: {
        let x = 1;
        break;
      }
      case 2: {
        const y = 2;
        break;
      }
      case 3: {
        function f() {
          // ...
        }
        break;
      }
      case 4:
        bar();
        break;
      default: {
        class C {}
      }
    }
    

  • 15.6 三元组应该不能嵌套,通常是单行表达式。

    eslint 规则:no-nested-ternary

    // bad
    const foo = maybe1 > maybe2
      ? "bar"
      : value1 > value2 ? "baz" : null;
    
    // better
    const maybeNull = value1 > value2 ? 'baz' : null;
    
    const foo = maybe1 > maybe2
      ? 'bar'
      : maybeNull;
    
    // best
    const maybeNull = value1 > value2 ? 'baz' : null;
    
    const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
    

  • 15.7 避免不需要三元语句。

    eslint 规则:no-unneeded-ternary

    // bad
    const foo = a ? a : b;
    const bar = c ? true : false;
    const baz = c ? false : true;
    
    // good
    const foo = a || b;
    const bar = Boolean(c);
    const baz = !c;
    

⬆ 返回顶部

Blocks

  • 16.1 在所有多行块中使用大括号。

    // bad
    if (test)
      return false;
    
    // good
    if (test) return false;
    
    // good
    if (test) {
      return false;
    }
    
    // bad
    function foo() { return false; }
    
    // good
    function bar() {
      return false;
    }
    

  • 16.2 如果你在 ifelse 中使用多行代码块,将 elseif 代码块放在同一行右括号。 eslint:brace-style jscs:disallowNewlineBeforeBlockStatements

    // bad
    if (test) {
      thing1();
      thing2();
    }
    else {
      thing3();
    }
    
    // good
    if (test) {
      thing1();
      thing2();
    } else {
      thing3();
    }
    

⬆ 返回顶部

Comments

  • 17.1 使用/* * ... */ 用于多行注释。

    // bad
    // make() returns a new element
    // based on the passed in tag name
    //
    // @param {String} tag
    // @return {Element} element
    function make(tag) {
    
      // ...
    
      return element;
    }
    
    // good
    /**
     * make() returns a new element
     * based on the passed-in tag name
     */
    function make(tag) {
    
      // ...
    
      return element;
    }
    

  • 17.2 使用// 用于单行注释。 将单行评论放在评论主题上方的换行符上。 在注释之前放一个空行,除非它在块的第一行。

    // bad
    const active = true;  // is current tab
    
    // good
    // is current tab
    const active = true;
    
    // bad
    function getType() {
      console.log('fetching type...');
      // set the default type to 'no type'
      const type = this.type || 'no type';
    
      return type;
    }
    
    // good
    function getType() {
      console.log('fetching type...');
    
      // set the default type to 'no type'
      const type = this.type || 'no type';
    
      return type;
    }
    
    // also good
    function getType() {
      // set the default type to 'no type'
      const type = this.type || 'no type';
    
      return type;
    }
    
  • 17.3 所有评论都以空格开头,以便于阅读。 eslint:spaced-comment

    // bad
    //is current tab
    const active = true;
    
    // good
    // is current tab
    const active = true;
    
    // bad
    /**
     *make() returns a new element
     *based on the passed-in tag name
     */
    function make(tag) {
    
      // ...
    
      return element;
    }
    
    // good
    /**
     * make() returns a new element
     * based on the passed-in tag name
     */
    function make(tag) {
    
      // ...
    
      return element;
    }
    

    < /a>

  • 17.4FIXMETODO< 作为评论的前缀/code> 帮助其他开发人员快速了解您是在指出需要重新审视的问题,还是在建议需要实施的问题解决方案。 这些与常规评论不同,因为它们是可操作的。 这些操作是 FIXME: -- need to figure this outTODO: -- need to implement

  • 17.5 使用// FIXME: 注释问题。

    class Calculator extends Abacus {
      constructor() {
        super();
    // FIXME: shouldn't use a global here
    total = 0;
    
    } }

  • 17.6 使用// TODO: 注释问题的解决方案。

    class Calculator extends Abacus {
      constructor() {
        super();
    // TODO: total should be configurable by an options param
    this.total = 0;
    
    } }

⬆ 返回顶部

Whitespace

  • 18.1 使用软制表符(空格字符)设置为 2 个空格。 eslint:缩进 jscs:validateIndentation

    // bad
    function foo() {
    ∙∙∙∙let name;
    }
    
    // bad
    function bar() {
    ∙let name;
    }
    
    // good
    function baz() {
    ∙∙let name;
    }
    

  • 18.2 在大括号前放置 1 个空格。 eslint:space-before-blocks jscs:requireSpaceBeforeBlockStatements

    // bad
    function test(){
      console.log('test');
    }
    
    // good
    function test() {
      console.log('test');
    }
    
    // bad
    dog.set('attr',{
      age: '1 year',
      breed: 'Bernese Mountain Dog',
    });
    
    // good
    dog.set('attr', {
      age: '1 year',
      breed: 'Bernese Mountain Dog',
    });
    

  • 18.3 在控制语句(if, while等)。 在函数调用和声明中,参数列表和函数名之间不要有空格。 eslint:keyword-spacing jscs:requireSpaceAfterKeywords

    // bad
    if(isJedi) {
      fight ();
    }
    
    // good
    if (isJedi) {
      fight();
    }
    
    // bad
    function fight () {
      console.log ('Swooosh!');
    }
    
    // good
    function fight() {
      console.log('Swooosh!');
    }
    

  • 18.4 用空格分隔运算符。 eslint:space-infix-ops jscs:requireSpaceBeforeBinaryOperatorsrequireSpaceAfterBinaryOperators< /code>

    // bad
    const x=y+5;
    
    // good
    const x = y + 5;
    

  • 18.5 以单个换行符结束文件。 eslint: [eol-last], vscode: "files.insertFinalNewline": true (https://github.com/eslint/eslint/blob/master/docs/ rules/eol-last.md)

    // bad
    import { es6 } from './AirbnbStyleGuide';
      // ...
    export default es6;
    
    // bad
    import { es6 } from './AirbnbStyleGuide';
      // ...
    export default es6;↵
    ↵
    
    // good
    import { es6 } from './AirbnbStyleGuide';
      // ...
    export default es6;↵
    

  • 18.6 在制作长方法链(超过 2 个方法链)时使用缩进。 使用前导点 强调该行是方法调用,而不是新语句。 eslint:newline-per-chained-call no-whitespace-before-property

    // bad
    $('#items').find('.selected').highlight().end().find('.open').updateCount();
    
    // bad
    $('#items').
      find('.selected').
        highlight().
        end().
      find('.open').
        updateCount();
    
    // good
    $('#items')
      .find('.selected')
        .highlight()
        .end()
      .find('.open')
        .updateCount();
    
    // bad
    const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true)
        .attr('width', (radius + margin) * 2).append('svg:g')
        .attr('transform', `translate(${radius + margin},${radius + margin})`)
        .call(tron.led);
    
    // good
    const leds = stage.selectAll('.led')
        .data(data)
      .enter().append('svg:svg')
        .classed('led', true)
        .attr('width', (radius + margin) * 2)
      .append('svg:g')
        .attr('transform', `translate(${radius + margin},${radius + margin})`)
        .call(tron.led);
    
    // good
    const leds = stage.selectAll('.led').data(data);
    

  • 18.7 在块之后和下一个语句之前留一个空行。 jscs:requirePaddingNewLinesAfterBlocks

    // bad
    if (foo) {
      return bar;
    }
    return baz;
    
    // good
    if (foo) {
      return bar;
    }
    
    return baz;
    
    // bad
    const obj = {
      foo() {
      },
      bar() {
      },
    };
    return obj;
    
    // good
    const obj = {
      foo() {
      },
    
      bar() {
      },
    };
    
    return obj;
    
    // bad
    const arr = [
      function foo() {
      },
      function bar() {
      },
    ];
    return arr;
    
    // good
    const arr = [
      function foo() {
      },
    
      function bar() {
      },
    ];
    
    return arr;
    

    < a name="18.8">

  • 18.8 不要用空行填充你的块。 eslint:padded-blocks jscs:disallowPaddingNewlinesInBlocks

    // bad
    function bar() {
    
      console.log(foo);
    
    }
    
    // also bad
    if (baz) {
    
      console.log(qux);
    } else {
      console.log(foo);
    
    }
    
    // good
    function bar() {
      console.log(foo);
    }
    
    // good
    if (baz) {
      console.log(qux);
    } else {
      console.log(foo);
    }
    

  • 18.9 不要在括号内添加空格。 eslint:space-in-parens jscs:disallowSpacesInsideParentheses

    // bad
    function bar( foo ) {
      return foo;
    }
    
    // good
    function bar(foo) {
      return foo;
    }
    
    // bad
    if ( foo ) {
      console.log(foo);
    }
    
    // good
    if (foo) {
      console.log(foo);
    }
    

  • 18.10 不要在括号内添加空格。 eslint:array-bracket-spacing jscs:disallowSpacesInsideArrayBrackets

    ```java

17 Media JavaScript Style Guide

A mostly reasonable approach to JavaScript

This is a fork of airbnb/javascript

Installation / ESLint setup

npm install --save-dev @17media/eslint-config-17media
echo '{ "extends": "@17media/eslint-config-17media/browser" }' > .eslintrc

There are /browser and /node for different environment.

Other Style Guides

Table of Contents

  1. Types
  2. References
  3. Objects
  4. Arrays
  5. Destructuring
  6. Strings
  7. Functions
  8. Arrow Functions
  9. Classes & Constructors
  10. Modules
  11. Iterators and Generators
  12. Properties
  13. Variables
  14. Hoisting
  15. Comparison Operators & Equality
  16. Blocks
  17. Comments
  18. Whitespace
  19. Commas
  20. Semicolons
  21. Type Casting & Coercion
  22. Naming Conventions
  23. Accessors
  24. Events
  25. jQuery
  26. ECMAScript 5 Compatibility
  27. ECMAScript 6+ (ES 2015+) Styles
  28. Testing
  29. Performance
  30. Resources

Types

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

    • string
    • number
    • boolean
    • null
    • undefined
    const foo = 1;
    let bar = foo;
    
    bar = 9;
    
    console.log(foo, bar); // => 1, 9
    

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

    • object
    • array
    • function
    const foo = [1, 2];
    const bar = foo;
    
    bar[0] = 9;
    
    console.log(foo[0], bar[0]); // => 9, 9
    

⬆ back to top

References

  • 2.1 Use const for all of your references; avoid using var. eslint: prefer-const, no-const-assign

    Why? This ensures that you can't reassign your references, which can lead to bugs and difficult to comprehend code.

    // bad
    var a = 1;
    var b = 2;
    
    // good
    const a = 1;
    const b = 2;
    

  • 2.2 If you must reassign references, use let instead of var. eslint: no-var jscs: disallowVar

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

    // bad
    var count = 1;
    if (true) {
      count += 1;
    }
    
    // good, use the let.
    let count = 1;
    if (true) {
      count += 1;
    }
    

  • 2.3 Note that both let and const are block-scoped.

    // const and let only exist in the blocks they are defined in.
    {
      let a = 1;
      const b = 1;
    }
    console.log(a); // ReferenceError
    console.log(b); // ReferenceError
    

⬆ back to top

Objects

  • 3.1 Use the literal syntax for object creation. eslint: no-new-object

    // bad
    const item = new Object();
    
    // good
    const item = {};
    

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

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

    function getKey(k) {
      return `a key named ${k}`;
    }
    
    // bad
    const obj = {
      id: 5,
      name: 'San Francisco',
    };
    obj[getKey('enabled')] = true;
    
    // good
    const obj = {
      id: 5,
      name: 'San Francisco',
      [getKey('enabled')]: true,
    };
    

  • 3.3 Use object method shorthand. eslint: object-shorthand jscs: requireEnhancedObjectLiterals

    // bad
    const atom = {
      value: 1,
    
      addValue: function (value) {
        return atom.value + value;
      },
    };
    
    // good
    const atom = {
      value: 1,
    
      addValue(value) {
        return atom.value + value;
      },
    };
    

  • 3.4 Use property value shorthand. eslint: object-shorthand jscs: requireEnhancedObjectLiterals

    Why? It is shorter to write and descriptive.

    const lukeSkywalker = 'Luke Skywalker';
    
    // bad
    const obj = {
      lukeSkywalker: lukeSkywalker,
    };
    
    // good
    const obj = {
      lukeSkywalker,
    };
    

  • 3.6 Only quote properties that are invalid identifiers. eslint: quote-props jscs: disallowQuotedKeysInObjects

    Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.

    // bad
    const bad = {
      'foo': 3,
      'bar': 4,
      'data-blah': 5,
    };
    
    // good
    const good = {
      foo: 3,
      bar: 4,
      'data-blah': 5,
    };
    

  • 3.7 Do not call Object.prototype methods directly, such as hasOwnProperty, propertyIsEnumerable, and isPrototypeOf.

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

    // bad
    console.log(object.hasOwnProperty(key));
    
    // good
    console.log(Object.prototype.hasOwnProperty.call(object, key));
    
    // best
    const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
    /* or */
    import has from 'has';
    // ...
    console.log(has.call(object, key));
    

  • 3.8 Prefer the object spread operator over Object.assign to shallow-copy objects. Use the object rest operator to get a new object with certain properties omitted.

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

⬆ back to top

Arrays

  • 4.1 Use the literal syntax for array creation. eslint: no-array-constructor

    // bad
    const items = new Array();
    
    // good
    const items = [];
    

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

    const someStack = [];
    
    // bad
    someStack[someStack.length] = 'abracadabra';
    
    // good
    someStack.push('abracadabra');
    

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

    // bad
    const len = items.length;
    const itemsCopy = [];
    let i;
    
    for (i = 0; i < len; i += 1) {
      itemsCopy[i] = items[i];
    }
    
    // good
    const itemsCopy = [...items];
    

  • 4.4 To convert an array-like object to an array, use Array.from.

    const foo = document.querySelectorAll('.foo');
    const nodes = Array.from(foo);
    

  • 4.5 Use return statements in array method callbacks. It's ok to omit the return if the function body consists of a single statement following 8.2. eslint: array-callback-return

    // good
    [1, 2, 3].map((x) => {
      const y = x + 1;
      return x * y;
    });
    
    // good
    [1, 2, 3].map(x => x + 1);
    
    // bad
    const flat = {};
    [[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
      const flatten = memo.concat(item);
      flat[index] = flatten;
    });
    
    // good
    const flat = {};
    [[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
      const flatten = memo.concat(item);
      flat[index] = flatten;
      return flatten;
    });
    
    // bad
    inbox.filter((msg) => {
      const { subject, author } = msg;
      if (subject === 'Mockingbird') {
        return author === 'Harper Lee';
      } else {
        return false;
      }
    });
    
    // good
    inbox.filter((msg) => {
      const { subject, author } = msg;
      if (subject === 'Mockingbird') {
        return author === 'Harper Lee';
      }
    
      return false;
    });
    

⬆ back to top

  • 4.6 Use line breaks after open and before close array brackets if an array has multiple lines
  // bad
  const arr = [
    [0, 1], [2, 3], [4, 5],
  ];

  const objectInArray = [{
    id: 1,
  }, {
    id: 2,
  }];

  const numberInArray = [
    1, 2,
  ];

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

  const objectInArray = [
    {
      id: 1,
    },
    {
      id: 2,
    },
  ];

  const numberInArray = [
    1,
    2,
  ];

⬆ back to top

Destructuring

  • 5.1 Use object destructuring when accessing and using multiple properties of an object. jscs: requireObjectDestructuring

    Why? Destructuring saves you from creating temporary references for those properties.

    // bad
    function getFullName(user) {
      const firstName = user.firstName;
      const lastName = user.lastName;
    
      return `${firstName} ${lastName}`;
    }
    
    // good
    function getFullName(user) {
      const { firstName, lastName } = user;
      return `${firstName} ${lastName}`;
    }
    
    // good
    function getFullName({ firstName, lastName }) {
      return `${firstName} ${lastName}`;
    }
    

  • 5.2 Use array destructuring. jscs: requireArrayDestructuring

    const arr = [1, 2, 3, 4];
    
    // bad
    const first = arr[0];
    const second = arr[1];
    
    // good
    const [first, second] = arr;
    

  • 5.3 Use object destructuring for multiple return values, not array destructuring. jscs: disallowArrayDestructuringReturn

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

    // bad
    function processInput(input) {
      // then a miracle occurs
      return [left, right, top, bottom];
    }
    
    // the caller needs to think about the order of return data
    const [left, __, top] = processInput(input);
    
    // good
    function processInput(input) {
      // then a miracle occurs
      return { left, right, top, bottom };
    }
    
    // the caller selects only the data they need
    const { left, top } = processInput(input);
    

⬆ back to top

Strings

  • 6.1 Use single quotes '' for strings. eslint: quotes jscs: validateQuoteMarks

    // bad
    const name = "Capt. Janeway";
    
    // bad - template literals should contain interpolation or newlines
    const name = `Capt. Janeway`;
    
    // good
    const name = 'Capt. Janeway';
    

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

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

    // bad
    const errorMessage = 'This is a super long error that was thrown because \
    of Batman. When you stop to think about how Batman had anything to do \
    with this, you would get nowhere \
    fast.';
    
    // bad
    const errorMessage = 'This is a super long error that was thrown because ' +
      'of Batman. When you stop to think about how Batman had anything to do ' +
      'with this, you would get nowhere fast.';
    
    // good
    const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
    

  • 6.3 When programmatically building up strings, use template strings instead of concatenation. eslint: prefer-template template-curly-spacing jscs: requireTemplateStrings

    Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.

    // bad
    function sayHi(name) {
      return 'How are you, ' + name + '?';
    }
    
    // bad
    function sayHi(name) {
      return ['How are you, ', name, '?'].join();
    }
    
    // bad
    function sayHi(name) {
      return `How are you, ${ name }?`;
    }
    
    // good
    function sayHi(name) {
      return `How are you, ${name}?`;
    }
    

  • 6.4 Never use eval() on a string, it opens too many vulnerabilities.

  • 6.5 Do not unnecessarily escape characters in strings. eslint: no-useless-escape

    Why? Backslashes harm readability, thus they should only be present when necessary.

    // bad
    const foo = '\'this\' \i\s \"quoted\"';
    
    // good
    const foo = '\'this\' is "quoted"';
    const foo = `my name is '${name}'`;
    

⬆ back to top

Functions

  • 7.1 Use named function expressions instead of function declarations. eslint: func-style jscs: disallowFunctionDeclarations

    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 name the expression - anonymous functions can make it harder to locate the problem in an Error's call stack. (Discussion)

    // bad
    const foo = function () {
      // ...
    };
    
    // okay
    function foo() {
      // ...
    }
    
    // good
    const foo = function bar() {
      // ...
    };
    

  • 7.2 Wrap immediately invoked function expressions in parentheses. eslint: wrap-iife jscs: requireParenthesesAroundIIFE

    Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this. Note that in a world with modules everywhere, you almost never need an IIFE.

    // immediately-invoked function expression (IIFE)
    (function () {
      console.log('Welcome to the Internet. Please follow me.');
    }());
    

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

  • 7.4 Note: ECMA-262 defines a block as a list of statements. A function declaration is not a statement. Read ECMA-262's note on this issue.

    // bad
    if (currentUser) {
      function test() {
        console.log('Nope.');
      }
    }
    
    // good
    let test;
    if (currentUser) {
      test = () => {
        console.log('Yup.');
      };
    }
    

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

    // bad
    function foo(name, options, arguments) {
      // ...
    }
    
    // good
    function foo(name, options, args) {
      // ...
    }
    

  • 7.6 Never use arguments, opt to use rest syntax ... instead. eslint: prefer-rest-params

    Why? ... is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like like arguments.

    // bad
    function concatenateAll() {
      const args = Array.prototype.slice.call(arguments);
      return args.join('');
    }
    
    // good
    function concatenateAll(...args) {
      return args.join('');
    }
    

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

    // really bad
    function handleThings(opts) {
      // No! We shouldn't mutate function arguments.
      // Double bad: if opts is falsy it'll be set to an object which may
      // be what you want but it can introduce subtle bugs.
      opts = opts || {};
      // ...
    }
    
    // still bad
    function handleThings(opts) {
      if (opts === void 0) {
        opts = {};
      }
      // ...
    }
    
    // good
    function handleThings(opts = {}) {
      // ...
    }
    

  • 7.8 Avoid side effects with default parameters.

    Why? They are confusing to reason about.

    var b = 1;
    // bad
    function count(a = b++) {
      console.log(a);
    }
    count();  // 1
    count();  // 2
    count(3); // 3
    count();  // 3
    

  • 7.9 Always put default parameters last.

    // bad
    function handleThings(opts = {}, name) {
      // ...
    }
    
    // good
    function handleThings(name, opts = {}) {
      // ...
    }
    

  • 7.10 Never use the Function constructor to create a new function. eslint: no-new-func

    Why? Creating a function in this way evaluates a string similarly to eval(), which opens vulnerabilities.

    // bad
    var add = new Function('a', 'b', 'return a + b');
    
    // still bad
    var subtract = Function('a', 'b', 'return a - b');
    

  • 7.11 Spacing in a function signature. eslint: space-before-function-paren space-before-blocks

    Why? Consistency is good, and you shouldn’t have to add or remove a space when adding or removing a name.

    // bad
    const f = function(){};
    const g = function (){};
    const h = function() {};
    
    // good
    const x = function () {};
    const y = function a() {};
    

  • 7.12 Never mutate parameters. eslint: no-param-reassign

    Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.

    // bad
    function f1(obj) {
      obj.key = 1;
    }
    
    // good
    function f2(obj) {
      const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;
    }
    

  • 7.13 Never reassign parameters. eslint: no-param-reassign

    Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the arguments object. It can also cause optimization issues, especially in V8.

    // bad
    function f1(a) {
      a = 1;
      // ...
    }
    
    function f2(a) {
      if (!a) { a = 1; }
      // ...
    }
    
    // good
    function f3(a) {
      const b = a || 1;
      // ...
    }
    
    function f4(a = 1) {
      // ...
    }
    

  • 7.14 Prefer the use of the spread operator ... to call variadic functions. eslint: prefer-spread

    Why? It's cleaner, you don't need to supply a context, and you can not easily compose new with apply.

    // bad
    const x = [1, 2, 3, 4, 5];
    console.log.apply(console, x);
    
    // good
    const x = [1, 2, 3, 4, 5];
    console.log(...x);
    
    // bad
    new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));
    
    // good
    new Date(...[2016, 8, 5]);
    

  • 7.15 Functions with multiline signatures, or invocations, should be indented just like every other multiline list in this guide: with each item on a line by itself, with a trailing comma on the last item.

    // bad
    function foo(bar,
                 baz,
                 quux) {
      // ...
    }
    
    // good
    function foo(
      bar,
      baz,
      quux,
    ) {
      // ...
    }
    
    // bad
    console.log(foo,
      bar,
      baz);
    
    // good
    console.log(
      foo,
      bar,
      baz,
    );
    

⬆ back to top

Arrow Functions

  • 8.1 When you must use function expressions (as when passing an anonymous function), use arrow function notation. eslint: prefer-arrow-callback, arrow-spacing jscs: requireArrowFunctions

    Why? It creates a version of the function that executes in the context of this, which is usually what you want, and is a more concise syntax.

    Why not? If you have a fairly complicated function, you might move that logic out into its own function declaration.

    // bad
    [1, 2, 3].map(function (x) {
      const y = x + 1;
      return x * y;
    });
    
    // good
    [1, 2, 3].map((x) => {
      const y = x + 1;
      return x * y;
    });
    

  • 8.2 If the function body consists of a single expression, omit the braces and use the implicit return. Otherwise, keep the braces and use a return statement. eslint: arrow-parens, arrow-body-style jscs: disallowParenthesesAroundArrowParam, requireShorthandArrowFunctions

    Why? Syntactic sugar. It reads well when multiple functions are chained together.

    // bad
    [1, 2, 3].map(number => {
      const nextNumber = number + 1;
      `A string containing the ${nextNumber}.`;
    });
    
    // good
    [1, 2, 3].map(number => `A string containing the ${number}.`);
    
    // good
    [1, 2, 3].map((number) => {
      const nextNumber = number + 1;
      return `A string containing the ${nextNumber}.`;
    });
    
    // good
    [1, 2, 3].map((number, index) => ({
      [index]: number,
    }));
    

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

    // bad
    ['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call(
        httpMagicObjectWithAVeryLongName,
        httpMethod,
      )
    );
    
    // good
    ['get', 'post', 'put'].map(httpMethod => (
      Object.prototype.hasOwnProperty.call(
        httpMagicObjectWithAVeryLongName,
        httpMethod,
      )
    ));
    

  • 8.4 If your function takes a single argument and doesn’t use braces, omit the parentheses. Otherwise, always include parentheses around arguments for clarity and consistency. Note: it is also acceptable to always use parentheses, in which case use the "always" option for eslint or do not include disallowParenthesesAroundArrowParam for jscs. eslint: arrow-parens jscs: disallowParenthesesAroundArrowParam

    Why? Less visual clutter.

    // bad
    [1, 2, 3].map((x) => x * x);
    
    // good
    [1, 2, 3].map(x => x * x);
    
    // good
    [1, 2, 3].map(number => (
      `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`
    ));
    
    // bad
    [1, 2, 3].map(x => {
      const y = x + 1;
      return x * y;
    });
    
    // good
    [1, 2, 3].map((x) => {
      const y = x + 1;
      return x * y;
    });
    

  • 8.5 Avoid confusing arrow function syntax (=>) with comparison operators (<=, >=). eslint: no-confusing-arrow

    // bad
    const itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize;
    
    // bad
    const itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize;
    
    // good
    const itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize);
    
    // good
    const itemHeight = (item) => {
      const { height, largeSize, smallSize } = item;
      return height > 256 ? largeSize : smallSize;
    };
    

⬆ back to top

Classes & Constructors

  • 9.1 Always use class. Avoid manipulating prototype directly.

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

    // bad
    function Queue(contents = []) {
      this.queue = [...contents];
    }
    Queue.prototype.pop = function () {
      const value = this.queue[0];
      this.queue.splice(0, 1);
      return value;
    };
    
    
    // good
    class Queue {
      constructor(contents = []) {
        this.queue = [...contents];
      }
      pop() {
        const value = this.queue[0];
        this.queue.splice(0, 1);
        return value;
      }
    }
    

  • 9.2 Use extends for inheritance.

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

    // bad
    const inherits = require('inherits');
    function PeekableQueue(contents) {
      Queue.apply(this, contents);
    }
    inherits(PeekableQueue, Queue);
    PeekableQueue.prototype.peek = function () {
      return this.queue[0];
    };
    
    // good
    class PeekableQueue extends Queue {
      peek() {
        return this.queue[0];
      }
    }
    

  • 9.3 Methods can return this to help with method chaining.

    // bad
    Jedi.prototype.jump = function () {
      this.jumping = true;
      return true;
    };
    
    Jedi.prototype.setHeight = function (height) {
      this.height = height;
    };
    
    const luke = new Jedi();
    luke.jump(); // => true
    luke.setHeight(20); // => undefined
    
    // good
    class Jedi {
      jump() {
        this.jumping = true;
        return this;
      }
    
      setHeight(height) {
        this.height = height;
        return this;
      }
    }
    
    const luke = new Jedi();
    
    luke.jump()
      .setHeight(20);
    

  • 9.4 It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.

    class Jedi {
      constructor(options = {}) {
        this.name = options.name || 'no name';
      }
    
      getName() {
        return this.name;
      }
    
      toString() {
        return `Jedi - ${this.getName()}`;
      }
    }
    

  • 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

    // bad
    class Jedi {
      constructor() {}
    
      getName() {
        return this.name;
      }
    }
    
    // bad
    class Rey extends Jedi {
      constructor(...args) {
        super(...args);
      }
    }
    
    // good
    class Rey extends Jedi {
      constructor(...args) {
        super(...args);
        this.name = 'Rey';
      }
    }
    

  • 9.6 Avoid duplicate class members. eslint: no-dupe-class-members

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

    // bad
    class Foo {
      bar() { return 1; }
      bar() { return 2; }
    }
    
    // good
    class Foo {
      bar() { return 1; }
    }
    
    // good
    class Foo {
      bar() { return 2; }
    }
    

⬆ back to top

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.

    // bad
    const AirbnbStyleGuide = require('./AirbnbStyleGuide');
    module.exports = AirbnbStyleGuide.es6;
    
    // ok
    import AirbnbStyleGuide from './AirbnbStyleGuide';
    export default AirbnbStyleGuide.es6;
    
    // best
    import { es6 } from './AirbnbStyleGuide';
    export default es6;
    

  • 10.4 Only import from a path in one place. eslint: no-duplicate-imports

    Why? Having multiple lines that import from the same path can make code harder to maintain.

    // bad
    import foo from 'foo';
    // … some other imports … //
    import { named1, named2 } from 'foo';
    
    // good
    import foo, { named1, named2 } from 'foo';
    
    // good
    import foo, {
      named1,
      named2,
    } from 'foo';
    

  • 10.5 Do not export mutable bindings. eslint: import/no-mutable-exports

    Why? Mutation should be avoided in general, but in particular when exporting mutable bindings. While this technique may be needed for some special cases, in general, only constant references should be exported.

    // bad
    let foo = 3;
    export { foo };
    
    // good
    const foo = 3;
    export { foo };
    

  • 10.7 Put all imports above non-import statements. eslint: import/first

    Why? Since imports are hoisted, keeping them all at the top prevents surprising behavior.

    // bad
    import foo from 'foo';
    foo.init();
    
    import bar from 'bar';
    
    // good
    import foo from 'foo';
    import bar from 'bar';
    
    foo.init();
    

  • 10.8 Multiline imports should be indented just like multiline array and object literals.

    Why? The curly braces follow the same indentation rules as every other curly brace block in the style guide, as do the trailing commas.

    // bad
    import {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path';
    
    // good
    import {
      longNameA,
      longNameB,
      longNameC,
      longNameD,
      longNameE,
    } from 'path';
    

  • 10.8 Absolute import comes before relative import. eslint: import/first

    // bad
    import Component from './Component';
    import _ from 'lodash';
    
    // good
    import _ from 'lodash';
    import Component from './Component';
    

  • 10.8 Insert a new line after import statements. eslint: import/newline-after-import

    // bad
    import _ from 'lodash';
    import Component from './Component';
    const a = 5;
    
    // good
    import _ from 'lodash';
    import Component from './Component';
    
    const a = 5;
    

⬆ back to top

Iterators and Generators

  • 11.1 Don't use iterators. Prefer JavaScript's higher-order functions instead of loops like for-in or for-of. eslint: no-iterator no-restricted-syntax

    Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.

    Use map() / every() / filter() / find() / findIndex() / reduce() / some() / … to iterate over arrays, and Object.keys() / Object.values() / Object.entries() to produce arrays so you can iterate over objects.

    const numbers = [1, 2, 3, 4, 5];
    
    // bad
    let sum = 0;
    for (let num of numbers) {
      sum += num;
    }
    sum === 15;
    
    // good
    let sum = 0;
    numbers.forEach(num => sum += num);
    sum === 15;
    
    // best (use the functional force)
    const sum = numbers.reduce((total, num) => total + num, 0);
    sum === 15;
    
    // bad
    const increasedByOne = [];
    for (let i = 0; i < numbers.length; i++) {
      increasedByOne.push(numbers[i] + 1);
    }
    
    // good
    const increasedByOne = [];
    numbers.forEach(num => increasedByOne.push(num + 1));
    
    // best (keeping it functional)
    const increasedByOne = numbers.map(num => num + 1);
    

  • 11.2 Don't use generators for now. Unless libraries needed (e.g. redux-saga).

    Why? They don't transpile well to ES5.

  • 11.3 If you must use generators, or if you disregard our advice, make sure their function signature is spaced properly. eslint: generator-star-spacing

    Why? function and * are part of the same conceptual keyword - * is not a modifier for function, function* is a unique construct, different from function.

    // bad
    function * foo() {
      // ...
    }
    
    // bad
    const bar = function * () {
      // ...
    };
    
    // bad
    const baz = function *() {
      // ...
    };
    
    // bad
    const quux = function*() {
      // ...
    };
    
    // bad
    function*foo() {
      // ...
    }
    
    // bad
    function *foo() {
      // ...
    }
    
    // very bad
    function
    *
    foo() {
      // ...
    }
    
    // very bad
    const wat = function
    *
    () {
      // ...
    };
    
    // good
    function* foo() {
      // ...
    }
    
    // good
    const foo = function* () {
      // ...
    };
    

⬆ back to top

Properties

  • 12.1 Use dot notation when accessing properties. eslint: dot-notation jscs: requireDotNotation

    const luke = {
      jedi: true,
      age: 28,
    };
    
    // bad
    const isJedi = luke['jedi'];
    
    // good
    const isJedi = luke.jedi;
    

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

    const luke = {
      jedi: true,
      age: 28,
    };
    
    function getProp(prop) {
      return luke[prop];
    }
    
    const isJedi = getProp('jedi');
    

⬆ back to top

Variables

  • 13.1 Always use const or let to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that. eslint: no-undef prefer-const

    // bad
    superPower = new SuperPower();
    
    // good
    const superPower = new SuperPower();
    

  • 13.2 Use one const or let declaration per variable. eslint: one-var jscs: disallowMultipleVarDecl

    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.

    // bad
    const items = getItems(),
        goSportsTeam = true,
        dragonball = 'z';
    
    // bad
    // (compare to above, and try to spot the mistake)
    const items = getItems(),
        goSportsTeam = true;
        dragonball = 'z';
    
    // good
    const items = getItems();
    const goSportsTeam = true;
    const dragonball = 'z';
    

  • 13.3 Group all your consts and then group all your lets.

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

    // bad
    let i, len, dragonball,
        items = getItems(),
        goSportsTeam = true;
    
    // bad
    let i;
    const items = getItems();
    let dragonball;
    const goSportsTeam = true;
    let len;
    
    // good
    const goSportsTeam = true;
    const items = getItems();
    let dragonball;
    let i;
    let length;
    

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

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

    // bad - unnecessary function call
    function checkName(hasName) {
      const name = getName();
    
      if (hasName === 'test') {
        return false;
      }
    
      if (name === 'test') {
        this.setName('');
        return false;
      }
    
      return name;
    }
    
    // good
    function checkName(hasName) {
      if (hasName === 'test') {
        return false;
      }
    
      const name = getName();
    
      if (name === 'test') {
        this.setName('');
        return false;
      }
    
      return name;
    }
    

  • 13.5 Don't chain variable assignments.

    Why? Chaining variable assignments creates implicit global variables.

    // bad
    (function example() {
      // JavaScript interprets this as
      // let a = ( b = ( c = 1 ) );
      // The let keyword only applies to variable a; variables b and c become
      // global variables.
      let a = b = c = 1;
    }());
    
    console.log(a); // undefined
    console.log(b); // 1
    console.log(c); // 1
    
    // good
    (function example() {
      let a = 1;
      let b = a;
      let c = a;
    }());
    
    console.log(a); // undefined
    console.log(b); // undefined
    console.log(c); // undefined
    
    // the same applies for `const`
    

  • 13.6 Avoid using unary increments and decrements (++, --). Using it in for-loop is acceptable for general pratice (Though you should avoid using for-loop too). eslint: no-plusplus

    Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like num += 1 instead of num++ or num ++. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs.

    // bad
    const array = [1, 2, 3];
    let num = 1;
    num++;
    --num;
    
    // okay
    for (let i = 0; i < 10; i++) {
      console.log(i);
    }
    // better
    for (let i = 0; i < 10; i += 1) {
      console.log(i);
    }
    
    // good
    const array = [1, 2, 3];
    let num = 1;
    num += 1;
    num -= 1;
    
    const sum = array.reduce((a, b) => a + b, 0);
    const truthyCount = array.filter(Boolean).length;
    

⬆ back to top

Hoisting

  • 14.1 var declarations get hoisted to the top of their 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.

    // we know this wouldn't work (assuming there
    // is no notDefined global variable)
    function example() {
      console.log(notDefined); // => throws a ReferenceError
    }
    
    // creating a variable declaration after you
    // reference the variable will work due to
    // variable hoisting. Note: the assignment
    // value of `true` is not hoisted.
    function example() {
      console.log(declaredButNotAssigned); // => undefined
      var declaredButNotAssigned = true;
    }
    
    // the interpreter is hoisting the variable
    // declaration to the top of the scope,
    // which means our example could be rewritten as:
    function example() {
      let declaredButNotAssigned;
      console.log(declaredButNotAssigned); // => undefined
      declaredButNotAssigned = true;
    }
    
    // using const and let
    function example() {
      console.log(declaredButNotAssigned); // => throws a ReferenceError
      console.log(typeof declaredButNotAssigned); // => throws a ReferenceError
      const declaredButNotAssigned = true;
    }
    

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

    function example() {
      console.log(anonymous); // => undefined
    
      anonymous(); // => TypeError anonymous is not a function
    
      var anonymous = function () {
        console.log('anonymous function expression');
      };
    }
    

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

    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      superPower(); // => ReferenceError superPower is not defined
    
      var named = function superPower() {
        console.log('Flying');
      };
    }
    
    // the same is true when the function name
    // is the same as the variable name.
    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      var named = function named() {
        console.log('named');
      };
    }
    

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

    function example() {
      superPower(); // => Flying
    
      function superPower() {
        console.log('Flying');
      }
    }
    
  • For more information refer to JavaScript Scoping & Hoisting by Ben Cherry.

⬆ back to top

Comparison Operators & Equality

  • 15.1 Use === and !== over == and !=. eslint: eqeqeq

  • 15.2 Conditional statements such as the if statement evaluate their expression using coercion with the ToBoolean abstract method and always follow these simple rules:

    • Objects evaluate to true
    • Undefined evaluates to false
    • Null evaluates to false
    • Booleans evaluate to the value of the boolean
    • Numbers evaluate to false if +0, -0, or NaN, otherwise true
    • Strings evaluate to false if an empty string '', otherwise true
    if ([0] && []) {
      // true
      // an array (even an empty one) is an object, objects will evaluate to true
    }
    

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

    // bad
    if (isValid === true) {
      // ...
    }
    
    // good
    if (isValid) {
      // ...
    }
    
    // bad
    if (name) {
      // ...
    }
    
    // good
    if (name !== '') {
      // ...
    }
    
    // bad
    if (collection.length) {
      // ...
    }
    
    // good
    if (collection.length > 0) {
      // ...
    }
    

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

  • 15.5 Use braces to create blocks in case and default clauses that contain lexical declarations (e.g. let, const, function, and class).

    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.

    eslint rules: no-case-declarations.

    // bad
    switch (foo) {
      case 1:
        let x = 1;
        break;
      case 2:
        const y = 2;
        break;
      case 3:
        function f() {
          // ...
        }
        break;
      default:
        class C {}
    }
    
    // good
    switch (foo) {
      case 1: {
        let x = 1;
        break;
      }
      case 2: {
        const y = 2;
        break;
      }
      case 3: {
        function f() {
          // ...
        }
        break;
      }
      case 4:
        bar();
        break;
      default: {
        class C {}
      }
    }
    

  • 15.6 Ternaries should not be nested and generally be single line expressions.

    eslint rules: no-nested-ternary.

    // bad
    const foo = maybe1 > maybe2
      ? "bar"
      : value1 > value2 ? "baz" : null;
    
    // better
    const maybeNull = value1 > value2 ? 'baz' : null;
    
    const foo = maybe1 > maybe2
      ? 'bar'
      : maybeNull;
    
    // best
    const maybeNull = value1 > value2 ? 'baz' : null;
    
    const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
    

  • 15.7 Avoid unneeded ternary statements.

    eslint rules: no-unneeded-ternary.

    // bad
    const foo = a ? a : b;
    const bar = c ? true : false;
    const baz = c ? false : true;
    
    // good
    const foo = a || b;
    const bar = Boolean(c);
    const baz = !c;
    

⬆ back to top

Blocks

  • 16.1 Use braces with all multi-line blocks.

    // bad
    if (test)
      return false;
    
    // good
    if (test) return false;
    
    // good
    if (test) {
      return false;
    }
    
    // bad
    function foo() { return false; }
    
    // good
    function bar() {
      return false;
    }
    

  • 16.2 If you're using multi-line blocks with if and else, put else on the same line as your if block's closing brace. eslint: brace-style jscs: disallowNewlineBeforeBlockStatements

    // bad
    if (test) {
      thing1();
      thing2();
    }
    else {
      thing3();
    }
    
    // good
    if (test) {
      thing1();
      thing2();
    } else {
      thing3();
    }
    

⬆ back to top

Comments

  • 17.1 Use /** ... */ for multi-line comments.

    // bad
    // make() returns a new element
    // based on the passed in tag name
    //
    // @param {String} tag
    // @return {Element} element
    function make(tag) {
    
      // ...
    
      return element;
    }
    
    // good
    /**
     * make() returns a new element
     * based on the passed-in tag name
     */
    function make(tag) {
    
      // ...
    
      return element;
    }
    

  • 17.2 Use // for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it's on the first line of a block.

    // bad
    const active = true;  // is current tab
    
    // good
    // is current tab
    const active = true;
    
    // bad
    function getType() {
      console.log('fetching type...');
      // set the default type to 'no type'
      const type = this.type || 'no type';
    
      return type;
    }
    
    // good
    function getType() {
      console.log('fetching type...');
    
      // set the default type to 'no type'
      const type = this.type || 'no type';
    
      return type;
    }
    
    // also good
    function getType() {
      // set the default type to 'no type'
      const type = this.type || 'no type';
    
      return type;
    }
    
  • 17.3 Start all comments with a space to make it easier to read. eslint: spaced-comment

    // bad
    //is current tab
    const active = true;
    
    // good
    // is current tab
    const active = true;
    
    // bad
    /**
     *make() returns a new element
     *based on the passed-in tag name
     */
    function make(tag) {
    
      // ...
    
      return element;
    }
    
    // good
    /**
     * make() returns a new element
     * based on the passed-in tag name
     */
    function make(tag) {
    
      // ...
    
      return element;
    }
    

  • 17.4 Prefixing your comments with FIXME or TODO helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are FIXME: -- need to figure this out or TODO: -- need to implement.

  • 17.5 Use // FIXME: to annotate problems.

    class Calculator extends Abacus {
      constructor() {
        super();
    // FIXME: shouldn't use a global here
    total = 0;
    
    } }

  • 17.6 Use // TODO: to annotate solutions to problems.

    class Calculator extends Abacus {
      constructor() {
        super();
    // TODO: total should be configurable by an options param
    this.total = 0;
    
    } }

⬆ back to top

Whitespace

  • 18.1 Use soft tabs (space character) set to 2 spaces. eslint: indent jscs: validateIndentation

    // bad
    function foo() {
    ∙∙∙∙let name;
    }
    
    // bad
    function bar() {
    ∙let name;
    }
    
    // good
    function baz() {
    ∙∙let name;
    }
    

  • 18.2 Place 1 space before the leading brace. eslint: space-before-blocks jscs: requireSpaceBeforeBlockStatements

    // bad
    function test(){
      console.log('test');
    }
    
    // good
    function test() {
      console.log('test');
    }
    
    // bad
    dog.set('attr',{
      age: '1 year',
      breed: 'Bernese Mountain Dog',
    });
    
    // good
    dog.set('attr', {
      age: '1 year',
      breed: 'Bernese Mountain Dog',
    });
    

  • 18.3 Place 1 space before the opening parenthesis in control statements (if, while etc.). Place no space between the argument list and the function name in function calls and declarations. eslint: keyword-spacing jscs: requireSpaceAfterKeywords

    // bad
    if(isJedi) {
      fight ();
    }
    
    // good
    if (isJedi) {
      fight();
    }
    
    // bad
    function fight () {
      console.log ('Swooosh!');
    }
    
    // good
    function fight() {
      console.log('Swooosh!');
    }
    

  • 18.4 Set off operators with spaces. eslint: space-infix-ops jscs: requireSpaceBeforeBinaryOperators, requireSpaceAfterBinaryOperators

    // bad
    const x=y+5;
    
    // good
    const x = y + 5;
    

  • 18.5 End files with a single newline character. eslint: [eol-last], vscode: "files.insertFinalNewline": true (https://github.com/eslint/eslint/blob/master/docs/rules/eol-last.md)

    // bad
    import { es6 } from './AirbnbStyleGuide';
      // ...
    export default es6;
    
    // bad
    import { es6 } from './AirbnbStyleGuide';
      // ...
    export default es6;↵
    ↵
    
    // good
    import { es6 } from './AirbnbStyleGuide';
      // ...
    export default es6;↵
    

  • 18.6 Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which emphasizes that the line is a method call, not a new statement. eslint: newline-per-chained-call no-whitespace-before-property

    // bad
    $('#items').find('.selected').highlight().end().find('.open').updateCount();
    
    // bad
    $('#items').
      find('.selected').
        highlight().
        end().
      find('.open').
        updateCount();
    
    // good
    $('#items')
      .find('.selected')
        .highlight()
        .end()
      .find('.open')
        .updateCount();
    
    // bad
    const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true)
        .attr('width', (radius + margin) * 2).append('svg:g')
        .attr('transform', `translate(${radius + margin},${radius + margin})`)
        .call(tron.led);
    
    // good
    const leds = stage.selectAll('.led')
        .data(data)
      .enter().append('svg:svg')
        .classed('led', true)
        .attr('width', (radius + margin) * 2)
      .append('svg:g')
        .attr('transform', `translate(${radius + margin},${radius + margin})`)
        .call(tron.led);
    
    // good
    const leds = stage.selectAll('.led').data(data);
    

  • 18.7 Leave a blank line after blocks and before the next statement. jscs: requirePaddingNewLinesAfterBlocks

    // bad
    if (foo) {
      return bar;
    }
    return baz;
    
    // good
    if (foo) {
      return bar;
    }
    
    return baz;
    
    // bad
    const obj = {
      foo() {
      },
      bar() {
      },
    };
    return obj;
    
    // good
    const obj = {
      foo() {
      },
    
      bar() {
      },
    };
    
    return obj;
    
    // bad
    const arr = [
      function foo() {
      },
      function bar() {
      },
    ];
    return arr;
    
    // good
    const arr = [
      function foo() {
      },
    
      function bar() {
      },
    ];
    
    return arr;
    

  • 18.8 Do not pad your blocks with blank lines. eslint: padded-blocks jscs: disallowPaddingNewlinesInBlocks

    // bad
    function bar() {
    
      console.log(foo);
    
    }
    
    // also bad
    if (baz) {
    
      console.log(qux);
    } else {
      console.log(foo);
    
    }
    
    // good
    function bar() {
      console.log(foo);
    }
    
    // good
    if (baz) {
      console.log(qux);
    } else {
      console.log(foo);
    }
    

  • 18.9 Do not add spaces inside parentheses. eslint: space-in-parens jscs: disallowSpacesInsideParentheses

    // bad
    function bar( foo ) {
      return foo;
    }
    
    // good
    function bar(foo) {
      return foo;
    }
    
    // bad
    if ( foo ) {
      console.log(foo);
    }
    
    // good
    if (foo) {
      console.log(foo);
    }
    

  • 18.10 Do not add spaces inside brackets. eslint: array-bracket-spacing jscs: disallowSpacesInsideArrayBrackets

    ```java

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文