1. 首页

javascript代码规范,应该这样写

Airbnb JavaScript Style Guide() {

A mostly reasonable approach to JavaScript
一种写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.
注意:本指南假定你正在使用Babel并要求你使用babel-preset-airbnb或者其他相同的资源。并且假定你在你的应用中安装了shims/polyfills,使用airbnb-browser-shims或相同的功能

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. Control Statements(控制语句)
  18. Comments(注释)
  19. Whitespace(空白)
  20. Commas(逗号)
  21. Semicolons(分号)
  22. Type Casting & Coercion(类型转换和强制类型转换)
  23. Naming Conventions(命名规则)
  24. Accessors(存储器)
  25. Events(事件)
  26. jQuery
  27. ECMAScript 5 Compatibility
  28. ECMAScript 6+ (ES 2015+) Styles
  29. Standard Library(标准库)
  30. Testing(测试)
  31. Performance(性能)
  32. Resources(资源)

Types


1.1 Primitives: When you access a primitive type you work directly on its value.
原始值:当你访问一个原始类型的时候,你可以直接使用它的值

- `string`
- `number`
- `boolean`
- `null`
- `undefined`
- `symbol`

```javascript
const foo = 1;
let bar = foo;

bar = 9;

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

- Symbols cannot be faithfully polyfilled, so they should not be used when targeting browsers/environments that don’t support them natively.
- Symbols不能被完全的支持,所以不要在不支持的浏览器/环境使用它们


1.2 Complex: When you access a complex type you work on a reference to its value.
复杂类型:当你访问一个复杂类型时,你可以对它的值进行引用

- `object`
- `array`
- `function`

```javascript
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
使用const进行复制,避免使用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.
> why?这样能够确保不能修改你的引用,否则会导致bug或者难以理解的错误

```javascript
// 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
如果你一定需要对应用重新赋值,使用let来代替var

> Why? `let` is block-scoped rather than function-scoped like `var`.
> why?`let`是块级作用域而不是像`var`的函数作用域

```javascript
// 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.
注意:letconst都是块级作用域

```javascript
// 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
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Objects</h2>

<a name="objects--no-new"></a><a name="3.1"></a>
  - <a href="#objects--no-new">3.1</a> Use the literal syntax for object creation. eslint: <a href="https://eslint.org/docs/rules/no-new-object.html"><code>no-new-object</code></a>
    使用字面量语法来创建对象eslint: <a href="https://eslint.org/docs/rules/no-new-object.html"><code>no-new-object</code></a>

<pre><code>```javascript
// bad
const item = new Object();

// good
const item = {};
```
</code></pre>

<a name="es6-computed-properties"></a><a name="3.4"></a>
  - <a href="#es6-computed-properties">3.2</a> Use computed property names when creating objects with dynamic property names.
    在使用动态属性名来创建对象时使用计算属性名

<pre><code>> Why? They allow you to define all the properties of an object in one place.
> why?这样允许你在一个地方定义所有的属性名

```javascript
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,
};
```
</code></pre>

<a name="es6-object-shorthand"></a><a name="3.5"></a>
  - <a href="#es6-object-shorthand">3.3</a> Use object method shorthand. eslint: <a href="https://eslint.org/docs/rules/object-shorthand.html"><code>object-shorthand</code></a>
    使用对象方法的简写eslint: <a href="https://eslint.org/docs/rules/object-shorthand.html"><code>object-shorthand</code></a>

<pre><code>```javascript
// bad
const atom = {
  value: 1,

  addValue: function (value) {
    return atom.value + value;
  },
};

// good
const atom = {
  value: 1,

  addValue(value) {
    return atom.value + value;
  },
};
```
</code></pre>

<a name="es6-object-concise"></a><a name="3.6"></a>
  - <a href="#es6-object-concise">3.4</a> Use property value shorthand. eslint: <a href="https://eslint.org/docs/rules/object-shorthand.html"><code>object-shorthand</code></a>
    使用属性值的简写

<pre><code>> Why? It is shorter to write and descriptive.
> why?这可以使其写法和描述更短

```javascript
const lukeSkywalker = 'Luke Skywalker';

// bad
const obj = {
  lukeSkywalker: lukeSkywalker,
};

// good
const obj = {
  lukeSkywalker,
};
```
</code></pre>

<a name="objects--grouped-shorthand"></a><a name="3.7"></a>
  - <a href="#objects--grouped-shorthand">3.5</a> Group your shorthand properties at the beginning of your object declaration.
    在最初声明对象的时候将你的简写属性进行分组

<pre><code>> Why? It’s easier to tell which properties are using the shorthand.
> why?这样更容易知道那些属性是用了简写

```javascript
const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';

// bad
const obj = {
  episodeOne: 1,
  twoJediWalkIntoACantina: 2,
  lukeSkywalker,
  episodeThree: 3,
  mayTheFourth: 4,
  anakinSkywalker,
};

// good
const obj = {
  lukeSkywalker,
  anakinSkywalker,
  episodeOne: 1,
  twoJediWalkIntoACantina: 2,
  episodeThree: 3,
  mayTheFourth: 4,
};
```
</code></pre>

<a name="objects--quoted-props"></a><a name="3.8"></a>
  - <a href="#objects--quoted-props">3.6</a> Only quote properties that are invalid identifiers. eslint: <a href="https://eslint.org/docs/rules/quote-props.html"><code>quote-props</code></a>
    只使用引号标注无效标识符的属性eslint: <a href="https://eslint.org/docs/rules/quote-props.html"><code>quote-props</code></a>

<pre><code>> Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.
> why?总的来说,我们觉得这样更容易去阅读。它提升了语法的高亮显示,并且同样有利于js引擎的优化

```javascript
// 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. eslint: no-prototype-builtins
不要直接调用Object.prototype方法,例如shasOwnProperty, propertyIsEnumerableisPrototypeOf. eslint: no-prototype-builtins

> Why? These methods may be shadowed by properties on the object in question - consider `{ hasOwnProperty: false }` - or, the object may be a null object (`Object.create(null)`).
> why?这些方法可能会被以下问题对象的属性追踪,例如`{ hasOwnProperty: false }` 或者可能是一个空对象 ` Object`

```javascript
// 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'; // https://www.npmjs.com/package/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.
更推荐使用拓展运动符而不是[Object.assign]去浅拷贝一个对象。使用对象的rest运算符去获得一个确定没有被遗漏属性的对象

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

// bad
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 }
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Arrays</h2>

<a name="arrays--literals"></a><a name="4.1"></a>
  - <a href="#arrays--literals">4.1</a> Use the literal syntax for array creation. eslint: <a href="https://eslint.org/docs/rules/no-array-constructor.html"><code>no-array-constructor</code></a>
    使用字面量去声明一个数组

<pre><code>```javascript
// bad
const items = new Array();

// good
const items = [];
```
</code></pre>

<a name="arrays--push"></a><a name="4.2"></a>
  - <a href="#arrays--push">4.2</a> Use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push">Array#push</a> instead of direct assignment to add items to an array.
    使用<a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push">Array#push</a> 代替直接给数组添加项

<pre><code>```javascript
const someStack = [];

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

// good
someStack.push('abracadabra');
```
</code></pre>

<a name="es6-array-spreads"></a><a name="4.3"></a>
  - <a href="#es6-array-spreads">4.3</a> Use array spreads <code>...</code> to copy arrays.
     使用数组的展开方法...来拷贝数组

<pre><code>```javascript
// bad
const len = items.length;
const itemsCopy = [];
let i;

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

// good
const itemsCopy = [...items];
```
</code></pre>

<a name="arrays--from"></a>
  <a name="arrays--from-iterable"></a><a name="4.4"></a>
  - <a href="#arrays--from-iterable">4.4</a> To convert an iterable object to an array, use spreads <code>...</code> instead of <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from"><code>Array.from</code></a>.
    将一个类数组对象转换成数组,使用展开方法...代替<a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from"><code>Array.from</code></a>.

<pre><code>```javascript
const foo = document.querySelectorAll('.foo');

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

// best
const nodes = [...foo];
```
</code></pre>

<a name="arrays--from-array-like"></a>
  - <a href="#arrays--from-array-like">4.5</a> Use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from"><code>Array.from</code></a> for converting an array-like object to an array.
    使用<a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from"><code>Array.from</code></a>去转换一个类数组对象变成一个数组

<pre><code>```javascript
const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };

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

// good
const arr = Array.from(arrLike);
```
</code></pre>

<a name="arrays--mapping"></a>
  - <a href="#arrays--mapping">4.6</a> Use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from"><code>Array.from</code></a> instead of spread <code>...</code> for mapping over iterables, because it avoids creating an intermediate array.
    使用<a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from"><code>Array.from</code></a>代替数组展开方法去循环一个可迭代的对象,因为这可以避免产生一个中间数组

<pre><code>```javascript
// bad
const baz = [...foo].map(bar);

// good
const baz = Array.from(foo, bar);
```
</code></pre>

<a name="arrays--callback-return"></a><a name="4.5"></a>
  - <a href="#arrays--callback-return">4.7</a> 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 <a href="#arrows--implicit-return">8.2</a>. eslint: <a href="https://eslint.org/docs/rules/array-callback-return"><code>array-callback-return</code></a>
    在数组方法的回调方法中使用return语句,如果函数体由一个不返回副作用的单个语句组成,那么可以考虑省略掉return语句。eslint: <a href="https://eslint.org/docs/rules/array-callback-return"><code>array-callback-return</code></a>

<pre><code>```javascript
// good
[1, 2, 3].map((x) => {
  const y = x + 1;
  return x * y;
});

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

// bad - no returned value means `acc` becomes undefined after the first iteration
// 没有返回值意味着在第一次循环后,acc变成undefined
[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
  const flatten = acc.concat(item);
  acc[index] = flatten;
});

// good
[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
  const flatten = acc.concat(item);
  acc[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;
});
```
</code></pre>

<a name="arrays--bracket-newline"></a>
  - <a href="#arrays--bracket-newline">4.8</a> Use line breaks after open and before close array brackets if an array has multiple lines
    当数组有多行时,在数组开始和结尾的地方换行

<pre><code>```javascript
// 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,
];
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Destructuring(解构)</h2>

<a name="destructuring--object"></a><a name="5.1"></a>
  - <a href="#destructuring--object">5.1</a> Use object destructuring when accessing and using multiple properties of an object. eslint: <a href="https://eslint.org/docs/rules/prefer-destructuring"><code>prefer-destructuring</code></a>
    当从一个对象接受和使用多个属性的时候,使用对象额解构

<pre><code>> Why? Destructuring saves you from creating temporary references for those properties.
> why? 解构可以减少你为这个属性创建临时的引用

```javascript
// 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}`;
}

// best
function getFullName({ firstName, lastName }) {
  return `${firstName} ${lastName}`;
}
```
</code></pre>

<a name="destructuring--array"></a><a name="5.2"></a>
  - <a href="#destructuring--array">5.2</a> Use array destructuring. eslint: <a href="https://eslint.org/docs/rules/prefer-destructuring"><code>prefer-destructuring</code></a>
    使用数组的解构 eslint: <a href="https://eslint.org/docs/rules/prefer-destructuring"><code>prefer-destructuring</code></a>

<pre><code>```javascript
const arr = [1, 2, 3, 4];

// bad
const first = arr[0];
const second = arr[1];

// good
const [first, second] = arr;
```
</code></pre>

<a name="destructuring--object-over-array"></a><a name="5.3"></a>
  - <a href="#destructuring--object-over-array">5.3</a> Use object destructuring for multiple return values, not array destructuring.
    当返回多个值时,使用对象的解构,而不是数组的解构

<pre><code>> Why? You can add new properties over time or change the order of things without breaking call sites.
> why? 你可以添加或改变返回属性额度顺序,而不需要修改调用的地方。

```javascript
// 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);
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Strings</h2>

<a name="strings--quotes"></a><a name="6.1"></a>
  - <a href="#strings--quotes">6.1</a> Use single quotes <code>''</code> for strings. eslint: <a href="https://eslint.org/docs/rules/quotes.html"><code>quotes</code></a>
    对字符串使用单引号

<pre><code>```javascript
// bad
const name = "Capt. Janeway";

// bad - template literals should contain interpolation or newlines
// 模板字符串需要包含变量或者新的一行
const name = `Capt. Janeway`;

// good
const name = 'Capt. Janeway';
```
</code></pre>

<a name="strings--line-length"></a><a name="6.2"></a>
  - <a href="#strings--line-length">6.2</a> Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation.
    使行超过100个字符的字符串不应使用字符串连接跨多行写入。

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

```javascript
// 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.';
```
</code></pre>

<a name="es6-template-literals"></a><a name="6.4"></a>
  - <a href="#es6-template-literals">6.3</a> When programmatically building up strings, use template strings instead of concatenation. eslint: <a href="https://eslint.org/docs/rules/prefer-template.html"><code>prefer-template</code></a> <a href="https://eslint.org/docs/rules/template-curly-spacing"><code>template-curly-spacing</code></a>
    当使用编程模式创建字符串,使用模板字符串代替拼接。

<pre><code>> Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation .
> why? 模板字符串可以给你可读性更强,更简洁的代码,具有合适的换行和特征插值。

```javascript
// 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}?`;
}
```
</code></pre>

<a name="strings--eval"></a><a name="6.5"></a>
  - <a href="#strings--eval">6.4</a> Never use <code>eval()</code> on a string, it opens too many vulnerabilities. eslint: <a href="https://eslint.org/docs/rules/no-eval"><code>no-eval</code></a>
    千万不要对字符串使用<code>eval()</code>,这会导致太多问题。eslint: <a href="https://eslint.org/docs/rules/no-eval"><code>no-eval</code></a>

<a name="strings--escaping"></a>
  - <a href="#strings--escaping">6.5</a> Do not unnecessarily escape characters in strings. eslint: <a href="https://eslint.org/docs/rules/no-useless-escape"><code>no-useless-escape</code></a>
    不要转义没有必要的字符

<pre><code>> Why? Backslashes harm readability, thus they should only be present when necessary.
> why? 反斜杠难以阅读,只有在必须的时候再使用它们

```javascript
// bad
const foo = '\'this\' \i\s \"quoted\"';

// good
const foo = '\'this\' is "quoted"';
const foo = `my name is '${name}'`;
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Functions</h2>

<a name="functions--declarations"></a><a name="7.1"></a>
  - <a href="#functions--declarations">7.1</a> Use named function expressions instead of function declarations. eslint: <a href="https://eslint.org/docs/rules/func-style"><code>func-style</code></a>
    使用命名的函数表达式代替函数命名

<pre><code>> Why? Function declarations are hoisted, which means that it’s easy - too easy - to reference the function before it is defined in the file. This harms readability and maintainability. If you find that a function’s definition is large or complex enough that it is interfering with understanding the rest of the file, then perhaps it’s time to extract it to its own module! Don’t forget to explicitly name the expression, regardless of whether or not the name is inferred from the containing variable (which is often the case in modern browsers or when using compilers such as Babel). This eliminates any assumptions made about the Error’s call stack. ([Discussion](https://github.com/airbnb/javascript/issues/794))
> why? 函数声明会被提升,这意味着这非常容易在这个函数被声明之前去调用它。这会使代码可读性变差和难以维护。如果你发现一个函数的定义已经大和复杂的影响到对剩余文件的理解。那么是时候将它们提取到自己的模块中。不要忘了明确地给这个函数命名,不管它的名字中是否含有变量(在现代浏览器中经常是这样,或者在使用诸如Babel之类的编译器时)。这消除了对错误的调用堆栈的任何假设。

```javascript
// bad
function foo() {
  // ...
}

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

// good
// lexical name distinguished from the variable-referenced invocation(s)
const short = function longUniqueMoreDescriptiveLexicalFoo() {
  // ...
};
```
</code></pre>

<a name="functions--iife"></a><a name="7.2"></a>
  - <a href="#functions--iife">7.2</a> Wrap immediately invoked function expressions in parentheses. eslint: <a href="https://eslint.org/docs/rules/wrap-iife.html"><code>wrap-iife</code></a>
    将立即执行函数用圆括号包裹起来

<pre><code>> 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.
> why? 一个立即执行函数是一个单元-被包裹起来,并且拥有括号调用, 在括号内, 清晰的表达式。 请注意,在一个到处都是模块的世界中,您几乎不需要一个 IIFE 。

```javascript
// immediately-invoked function expression (IIFE)
(function () {
  console.log('Welcome to the Internet. Please follow me.');
}());
```
</code></pre>

<a name="functions--in-blocks"></a><a name="7.3"></a>
  - <a href="#functions--in-blocks">7.3</a> Never declare a function in a non-function block (<code>if</code>, <code>while</code>, 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: <a href="https://eslint.org/docs/rules/no-loop-func.html"><code>no-loop-func</code></a>
    切记不要在非功能块中声明函数 (if, while, 等)。 将函数赋值给变量。 浏览器允许你这样做,但是他们都有不同的解释,这是个坏消息。

<a name="functions--note-on-blocks"></a><a name="7.4"></a>
  - <a href="#functions--note-on-blocks">7.4</a> <strong>Note:</strong> ECMA-262 defines a <code>block</code> as a list of statements. A function declaration is not a statement.
    注意ECMA-262将block定义为语句列表。一个函数声明不是一个语句

<pre><code>```javascript
// bad
if (currentUser) {
  function test() {
    console.log('Nope.');
  }
}

// good
let test;
if (currentUser) {
  test = () => {
    console.log('Yup.');
  };
}
```
</code></pre>

<a name="functions--arguments-shadow"></a><a name="7.5"></a>
  - <a href="#functions--arguments-shadow">7.5</a> Never name a parameter <code>arguments</code>. This will take precedence over the <code>arguments</code> object that is given to every function scope.
    千万不要将一个参数命名为<code>arguments</code>,这将会优先于函数中本来的arguments对象在整个函数作用域内

<pre><code>```javascript
// 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
千万不要使用arguments,使用扩展运算符...来代替。

> Why? `...` is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like like `arguments`.
> why? `...`明确的表达了你所想要的参数,并且,rest参数是一个真数组,而不像`arguments`只是一个伪数组。

```javascript
// 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.
使用默认参数语句,而不要去改变函数的参数

```javascript
// 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 当传入的opts为false时,同样会变成一个空对象
  // 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 = {}) {
  // ...
}
```
</code></pre>

<a name="functions--default-side-effects"></a><a name="7.8"></a>
  - <a href="#functions--default-side-effects">7.8</a> Avoid side effects with default parameters.
    避免默认参数带来的副作用

<pre><code>> Why? They are confusing to reason about.
> why? 这么很容易使人混淆

```javascript
var b = 1;
// bad
function count(a = b++) {
  console.log(a);
}
count();  // 1
count();  // 2
count(3); // 3
count();  // 3
```
</code></pre>

<a name="functions--defaults-last"></a><a name="7.9"></a>
  - <a href="#functions--defaults-last">7.9</a> Always put default parameters last.
    把参数默认语法放在最后

<pre><code>```javascript
// 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.
> why? 用这个方式创建函数,等同于对一个字符串使用`eval()`,这会导致很多问题

```javascript
// 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.
> why? 一致性很好,在删除或添加名称时不需要添加或删除空格。

```javascript
// 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.
> why? 改变一个当作参数传进来的对象的值,会对原始的调用造成意想不到的副作用。

```javascript
// 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.
> why? 重新赋值参数会导致意外的行为,尤其是在访问 arguments 对象的时候。 它还可能导致性能优化问题,尤其是在 V8 中。

```javascript
// 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`.
> why? 这样更加简洁,你不需要提供上下文,并且你也不能轻易的使用apply来new

```javascript
// 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. eslint: function-paren-newline
具有多行签名或者调用的函数应该像本指南中的其他多行列表一样缩进:在一行上只有一个条目,并且每个条目最后加上逗号。

```javascript
// 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 an anonymous function (as when passing an inline callback), use arrow function notation. eslint: prefer-arrow-callback, arrow-spacing
当你必须要使用一个匿名函数当传递内联函数时,使用箭头函数

> Why? It creates a version of the function that executes in the context of `this`, which is usually what you want, and is a more concise syntax.
> why? 它创建了一个在this执行上下文的函数版本,这通常是你想要的,并且这会使得语句更简洁

> Why not? If you have a fairly complicated function, you might move that logic out into its own named function expression.
> why not? 如果你有一个相当难懂的函数,你或许可以将逻辑移到属于以它自己命名的函数表达式

```javascript
// 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 statement returning an expression without side effects, omit the braces and use the implicit return. Otherwise, keep the braces and use a return statement. eslint: arrow-parens, arrow-body-style
如果函数内包含一个独立的语句,返回一个没有负责用的表达式,省略括号并使用隐式返回,或者保留括号并使用return语句

> Why? Syntactic sugar. It reads well when multiple functions are chained together.
> why? 语法糖,当多个函数被链接在一起这提高了可读性

```javascript
// 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,
}));

// No implicit return with side effects
function foo(callback) {
  const val = callback();
  if (val === true) {
    // Do something if callback returns true
  }
}

let bool = false;

// bad
foo(() => bool = true);

// good
foo(() => {
  bool = true;
});
```
</code></pre>

<a name="arrows--paren-wrap"></a><a name="8.3"></a>
  - <a href="#arrows--paren-wrap">8.3</a> In case the expression spans over multiple lines, wrap it in parentheses for better readability.
    万一表达式有多行,将它用括号包裹起来提高可读性

<pre><code>> Why? It shows clearly where the function starts and ends.
> why? 这样可以更清楚的看到函数的结尾和开始

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

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

<a name="arrows--one-arg-parens"></a><a name="8.4"></a>
  - <a href="#arrows--one-arg-parens">8.4</a> 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 <a href="https://eslint.org/docs/rules/arrow-parens#always">“always” option</a> for eslint. eslint: <a href="https://eslint.org/docs/rules/arrow-parens.html"><code>arrow-parens</code></a>
    如果你的函数只有一个参数,可以不使用括号。否则捏可以总是使用括号包裹以保证清晰和一致性。注意:每一次都使用括号时可以接受的。你可以使用<a href="https://eslint.org/docs/rules/arrow-parens#always">“always” option</a> for eslint. eslint: <a href="https://eslint.org/docs/rules/arrow-parens.html"><code>arrow-parens</code></a>

<pre><code>> Why? Less visual clutter.
> why? 减少视觉上的混乱

```javascript
// 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;
});
```
</code></pre>

<a name="arrows--confusing"></a><a name="8.5"></a>
  - <a href="#arrows--confusing">8.5</a> Avoid confusing arrow function syntax (<code>=></code>) with comparison operators (<code><=</code>, <code>>=</code>). eslint: <a href="https://eslint.org/docs/rules/no-confusing-arrow"><code>no-confusing-arrow</code></a>
    避免对箭头函数使用比较运算符,使人困惑难懂。

<pre><code>```javascript
// 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;
};
```
</code></pre>

<a name="whitespace--implicit-arrow-linebreak"></a>
  - <a href="#whitespace--implicit-arrow-linebreak">8.6</a> Enforce the location of arrow function bodies with implicit returns. eslint: <a href="https://eslint.org/docs/rules/implicit-arrow-linebreak"><code>implicit-arrow-linebreak</code></a>
    注意箭头函数体隐式返回的位置

<pre><code>```javascript
// bad
(foo) =>
  bar;

(foo) =>
  (bar);

// good
(foo) => bar;
(foo) => (bar);
(foo) => (
   bar
)
```

⬆ back to top

Classes & Constructors


9.1 Always use class. Avoid manipulating prototype directly.
使用class,避免直接使用prototype

> Why? `class` syntax is more concise and easier to reason about.
> why? `class`语法更加简洁并且可读性更好

```javascript
// 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.
使用extends代替inheritance

> Why? It is a built-in way to inherit prototype functionality without breaking `instanceof`.
> why? 它是一个内置的方法,可以在不破坏 instanceof 的情况下继承原型功能。

```javascript
// 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.
可以通过返回this来帮助函数链式调用

```javascript
// 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);
```
</code></pre>

<a name="constructors--tostring"></a><a name="9.4"></a>
  - <a href="#constructors--tostring">9.4</a> It’s okay to write a custom <code>toString()</code> method, just make sure it works successfully and causes no side effects.
    可以去写一个自定义的<code>toString()</code>方法,只需要确定它能正常工作并不会产生任何副作用

<pre><code>```javascript
class Jedi {
  constructor(options = {}) {
    this.name = options.name || 'no name';
  }

  getName() {
    return this.name;
  }

  toString() {
    return `Jedi - ${this.getName()}`;
  }
}
```
</code></pre>

<a name="constructors--no-useless"></a><a name="9.5"></a>
  - <a href="#constructors--no-useless">9.5</a> 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: <a href="https://eslint.org/docs/rules/no-useless-constructor"><code>no-useless-constructor</code></a>
    如果没有指定默认类构造函数,则ES2015提供一个默认类构造函数。因此,不需要提供空的构造函数,或者只委托给父类

<pre><code>```javascript
// 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';
  }
}
```
</code></pre>

<a name="classes--no-duplicate-members"></a>
  - <a href="#classes--no-duplicate-members">9.6</a> Avoid duplicate class members. eslint: <a href="https://eslint.org/docs/rules/no-dupe-class-members"><code>no-dupe-class-members</code></a>
    避免复制类的成员

<pre><code>> Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug.
> why? 复制类成员的声明会默认倾向于最后一个-有重复声明很可能是一个bug

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

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

// good
class Foo {
  bar() { return 2; }
}
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Modules</h2>

<a name="modules--use-them"></a><a name="10.1"></a>
  - <a href="#modules--use-them">10.1</a> Always use modules (<code>import</code>/<code>export</code>) over a non-standard module system. You can always transpile to your preferred module system.
    你可能经常使用模块(import/export)在非标准模块系统。你可以随时转向你更倾向的模块系统

<pre><code>> Why? Modules are the future, let’s start using the future now.
> why? 模块是未来的趋势。

```javascript
// 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;
```
</code></pre>

<a name="modules--no-wildcard"></a><a name="10.2"></a>
  - <a href="#modules--no-wildcard">10.2</a> Do not use wildcard imports.
    不要使用通配符进行引入

<pre><code>> Why? This makes sure you have a single default export.
> why? 这必须得保证你有一个单独的导出

```javascript
// bad
import * as AirbnbStyleGuide from './AirbnbStyleGuide';

// good
import AirbnbStyleGuide from './AirbnbStyleGuide';
```
</code></pre>

<a name="modules--no-export-from-import"></a><a name="10.3"></a>
  - <a href="#modules--no-export-from-import">10.3</a> And do not export directly from an import.
    不要直接从一个引入直接导出

<pre><code>> Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.
> why? 尽管少些一行会更简洁,但是用一个简洁的引入和一个简洁的导出可以使得代码一致性更好

```javascript
// bad
// filename es6.js
export { es6 as default } from './AirbnbStyleGuide';

// good
// filename es6.js
import { es6 } from './AirbnbStyleGuide';
export default es6;
```
</code></pre>

<a name="modules--no-duplicate-imports"></a>
  - <a href="#modules--no-duplicate-imports">10.4</a> Only import from a path in one place.
 eslint: <a href="https://eslint.org/docs/rules/no-duplicate-imports"><code>no-duplicate-imports</code></a>
    同一个路径只引入一次

<blockquote>
  Why? Having multiple lines that import from the same path can make code harder to maintain.
  why? 多次引入同一路径会使得代码编的难以维护
</blockquote>

<pre><code>```javascript
// 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';
```
</code></pre>

<a name="modules--no-mutable-exports"></a>
  - <a href="#modules--no-mutable-exports">10.5</a> Do not export mutable bindings.
 eslint: <a href="https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md"><code>import/no-mutable-exports</code></a>
    不要导出可变的引用

<blockquote>
  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.
  why? 总体来说需要避免变化,但是在导出可变引用时属于特殊情况。
  只有某些特殊的情况可能需要这种技巧,但是总的来说,只有常量可以被导出。
</blockquote>

<pre><code>```javascript
// bad
let foo = 3;
export { foo };

// good
const foo = 3;
export { foo };
```
</code></pre>

<a name="modules--prefer-default-export"></a>
  - <a href="#modules--prefer-default-export">10.6</a> In modules with a single export, prefer default export over named export.
 eslint: <a href="https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md"><code>import/prefer-default-export</code></a>
    在一个单一模块,导出默认模块而不是命名模块

<blockquote>
  Why? To encourage more files that only ever export one thing, which is better for readability and maintainability.
  why? 为了鼓励更多的文件只导出一件东西,这样可读性和可维护性更好。
      ```javascript
      // bad
      export function foo() {}


// good
export default function foo() {}
```
</code></pre>

<a name="modules--imports-first"></a>
  - <a href="#modules--imports-first">10.7</a> Put all <code>import</code>s above non-import statements.
 eslint: <a href="https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/first.md"><code>import/first</code></a>
    把所有导入语句放在非导入语句之上

<blockquote>
  Why? Since <code>import</code>s are hoisted, keeping them all at the top prevents surprising behavior.
  why? 自从<code>import</code>会被提升,保持它们都在最上面以防意外的情况出现。
</blockquote>

<pre><code>```javascript
// bad
import foo from 'foo';
foo.init();

import bar from 'bar';

// good
import foo from 'foo';
import bar from 'bar';

foo.init();
```
</code></pre>

<a name="modules--multiline-imports-over-newlines"></a>
  - <a href="#modules--multiline-imports-over-newlines">10.8</a> Multiline imports should be indented just like multiline array and object literals.
    多行的导入必须像多行数组和对象一样缩进,换行。

<pre><code>> Why? The curly braces follow the same indentation rules as every other curly brace block in the style guide, as do the trailing commas.
> why?大括号遵循与样式指南中其他大括号相同的缩进规则,以及逗号结尾。

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

// good
import {
  longNameA,
  longNameB,
  longNameC,
  longNameD,
  longNameE,
} from 'path';
```
</code></pre>

<a name="modules--no-webpack-loader-syntax"></a>
  - <a href="#modules--no-webpack-loader-syntax">10.9</a> Disallow Webpack loader syntax in module import statements.
 eslint: <a href="https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-webpack-loader-syntax.md"><code>import/no-webpack-loader-syntax</code></a>
    禁止在模块导入语句中使用webpack loader语法

<blockquote>
  Why? Since using Webpack syntax in the imports couples the code to a module bundler. Prefer using the loader syntax in <code>webpack.config.js</code>.
      更建议在<code>webpack.config.js</code>中使用loader语法
</blockquote>

<pre><code>```javascript
// bad
import fooSass from 'css!sass!foo.scss';
import barCss from 'style!css!bar.css';

// good
import fooSass from 'foo.scss';
import barCss from 'bar.css';
```

⬆ 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
不要使用 iterators,推荐使用js更高阶的函数来代替比如像for-in or for-of的循环

> Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
> why? 这强制让我们执行不可变规则,处理有返回值的简单函数比考虑副作用更容易。
> 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.
> 使用`map()` / `every()` / `filter()` / `find()` / `findIndex()` / `reduce()` / `some()` /去遍历数组, 使用`Object.keys()` / `Object.values()` / `Object.entries()` 去创造一个可以用来遍历对象的数组

```javascript
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.
现在不要使用生成器

> Why? They don’t transpile well to ES5.
> why? 它们还不能很好的转换成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`.
> why? function和*都是关键词,*不是function的修饰词,function*是一个与function不同的独特结构


```javascript
// 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
使用点号去访问一个属性

```javascript
const luke = {
  jedi: true,
  age: 28,
};

// bad
const isJedi = luke['jedi'];

// good
const isJedi = luke.jedi;
```
</code></pre>

<a name="properties--bracket"></a><a name="12.2"></a>
  - <a href="#properties--bracket">12.2</a> Use bracket notation <code>[]</code> when accessing properties with a variable.
    当使用一个变量去接受一个属性之的时候用[]

<pre><code>```javascript
const luke = {
  jedi: true,
  age: 28,
};

function getProp(prop) {
  return luke[prop];
}

const isJedi = getProp('jedi');
```
</code></pre>

<a name="es2016-properties--exponentiation-operator"></a>
  - <a href="#es2016-properties--exponentiation-operator">12.3</a> Use exponentiation operator <code>**</code> when calculating exponentiations. eslint: <a href="https://eslint.org/docs/rules/no-restricted-properties"><code>no-restricted-properties</code></a>.
    使用求幂运算符 ** 当你要计算求幂时

<pre><code>```javascript
// bad
const binary = Math.pow(2, 10);

// good
const binary = 2 ** 10;
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Variables</h2>

<a name="variables--const"></a><a name="13.1"></a>
  - <a href="#variables--const">13.1</a> Always use <code>const</code> or <code>let</code> 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: <a href="https://eslint.org/docs/rules/no-undef"><code>no-undef</code></a> <a href="https://eslint.org/docs/rules/prefer-const"><code>prefer-const</code></a>
    建议使用const和let来定义变量。不这样做会导致全局变量,我们想要尽可能避免污染全局命名空间。行星船长也这么警告过我们。

<pre><code>```javascript
// bad
superPower = new SuperPower();

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


- 13.2 Use one const or let declaration per variable or assignment. eslint: one-var
对每一个变量或者赋值使用一个const或者let

> 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.
> why?这样更容易去添加变量声明,并且你也不用担心那";"写成",",后者引入punctuation-only的差别。你同样可以通过debugger对每一个变量进行步进,而不是一次跳过所有的声明。

```javascript
// 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.
先将所有的const分组,然后讲所有的let进行分组。

> Why? This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
> why? 当以后您可能需要根据前面分配的变量分配变量时,这是很有帮助的。

```javascript
// 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.
> why? `let`和`const`是块级作用域而不是函数作用域

```javascript
// 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. eslint: no-multi-assign
不要链式的定义变量

> Why? Chaining variable assignments creates implicit global variables.
> why? 链式定义变量会隐式的生产全局变量

```javascript
// 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); // throws ReferenceError
console.log(b); // 1
console.log(c); // 1

// good
(function example() {
  let a = 1;
  let b = a;
  let c = a;
}());

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

// the same applies for `const`
```


- 13.6 Avoid using unary increments and decrements (++, --). eslint no-plusplus
避免使用一元加号和自增自减

> Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like `num += 1` instead of `num++` or `num ++`. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs.
> why? 根据eslint文档,一元加号和减号语句受自动分号插入的影响,会在应用中造成无声错误。使用类似`num += 1`来代替 `num++` or `num ++`也可以更好的表达含义。不允许使用一元加号,减号同样可以防止你无意中改变了你的变量值,这可能会造成预期之外的表现。

```javascript
// bad

const array = [1, 2, 3];
let num = 1;
num++;
--num;

let sum = 0;
let truthyCount = 0;
for (let i = 0; i < array.length; i++) {
  let value = array[i];
  sum += value;
  if (value) {
    truthyCount++;
  }
}

// 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;
```


- 13.7 Avoid linebreaks before or after = in an assignment. If your assignment violates max-len, surround the value in parens. eslint operator-linebreak.、
避免在赋值语句中=前后换行。实在长度超出了,请用括号将其包裹起来

> Why? Linebreaks surrounding `=` can obfuscate the value of an assignment.

```javascript
// bad
const foo =
  superLongLongLongLongLongLongLongLongFunctionName();

// bad
const foo
  = 'superLongLongLongLongLongLongLongLongString';

// good
const foo = (
  superLongLongLongLongLongLongLongLongFunctionName()
);

// good
const foo = 'superLongLongLongLongLongLongLongLongString';
```


- 13.8 Disallow unused variables. eslint: no-unused-vars
不允许未被使用的变量

> Why? Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
> why? 代码中有定义了而未被使用变量很可能是由于不完整的重构而导致的错误。这些变量不仅占用空间,还会对读者造成困惑。

```javascript
// bad

var some_unused_var = 42;

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

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

// Unused function arguments.
function getX(x, y) {
    return x;
}

// good

function getXPlusY(x, y) {
  return x + y;
}

var x = 1;
var y = a + 2;

alert(getXPlusY(x, y));

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

⬆ back to top

Hoisting(提升)


- 14.1 var declarations get hoisted to the top of their closest enclosing function scope, their assignment does not. const and let declarations are blessed with a new concept called Temporal Dead Zones (TDZ). It’s important to know why typeof is no longer safe.
var的声明会提升到最近闭合的函数作用于的顶部,但是它们的赋值并不会。const和let声明被赋予了一个新的概念叫暂时死亡区域?了解为什么typeof不再安全是很重要的。

```javascript
// 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;
}
```
</code></pre>

<a name="hoisting--anon-expressions"></a><a name="14.2"></a>
  - <a href="#hoisting--anon-expressions">14.2</a> Anonymous function expressions hoist their variable name, but not the function assignment.
    匿名函数的变量名会提升,但是函数体的赋值并不会

<pre><code>```javascript
function example() {
  console.log(anonymous); // => undefined

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

  var anonymous = function () {
    console.log('anonymous function expression');
  };
}
```
</code></pre>

<a name="hoisting--named-expresions"></a><a name="hoisting--named-expressions"></a><a name="14.3"></a>
  - <a href="#hoisting--named-expressions">14.3</a> Named function expressions hoist the variable name, not the function name or the function body.
    具名函数表达式提升变量名,而不是函数名或函数体。

<pre><code>```javascript
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');
  };
}
```
</code></pre>

<a name="hoisting--declarations"></a><a name="14.4"></a>
  - <a href="#hoisting--declarations">14.4</a> Function declarations hoist their name and the function body.
    函数声明不过会提升他们的名字还会提升函数体。

<pre><code>```javascript
function example() {
  superPower(); // => Flying

  function superPower() {
    console.log('Flying');
  }
}
```

⬆ 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:
条件语句(例如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**
- 如果为+0 -0 NaN则为false,其他为true
- **Strings** evaluate to **false** if an empty string `''`, otherwise **true**

```javascript
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.
可以使用简写来求布尔值,但比较字符串和数字要明确的写清楚。

```javascript
// 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). eslint: no-case-declarations
在 case 和 default 的子句中,如果存在声明 (例如. let, const, function, 和 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.
> why? 因为在整个switch快中,变量的声明都是可见的,虽然并未复制,以防影响到其他的case情况,使用大括号来创建快级作用域消除对其他case情况的影响。

```javascript
// 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: no-nested-ternary
三元表达式通常都是单行的,不应该被嵌套

```javascript
// bad
const foo = maybe1 > maybe2
  ? "bar"
  : value1 > value2 ? "baz" : null;

// split into 2 separated ternary expressions
const maybeNull = value1 > value2 ? 'baz' : null;

// better
const foo = maybe1 > maybe2
  ? 'bar'
  : maybeNull;

// best
const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
```
</code></pre>

<a name="comparison--unneeded-ternary"></a><a name="15.7"></a>
  - <a href="#comparison--unneeded-ternary">15.7</a> Avoid unneeded ternary statements. eslint: <a href="https://eslint.org/docs/rules/no-unneeded-ternary.html"><code>no-unneeded-ternary</code></a>
    避免没有必要的三元表达式

<pre><code>```javascript
// bad
const foo = a ? a : b;
const bar = c ? true : false;
const baz = c ? false : true;

// good
const foo = a || b;
const bar = !!c;
const baz = !c;
```
</code></pre>

<a name="comparison--no-mixed-operators"></a>
  - <a href="#comparison--no-mixed-operators">15.8</a> When mixing operators, enclose them in parentheses. The only exception is the standard arithmetic operators (<code>+</code>, <code>-</code>, <code>*</code>, & <code>/</code>) since their precedence is broadly understood. eslint: <a href="https://eslint.org/docs/rules/no-mixed-operators.html"><code>no-mixed-operators</code></a>
    当混合运算符时,将他们用圆括号包裹起来。除了标准运算符(<code>+</code>, <code>-</code>, <code>*</code>, & <code>/</code>) ,因为他们的优先级被广泛理解。

<pre><code>> Why? This improves readability and clarifies the developer’s intention.
> why? 这提高了代码的可读性并清楚的表达了

```javascript
// bad
const foo = a && b < 0 || c > 0 || d + 1 === 0;

// bad
const bar = a ** b - 5 % d;

// bad
// one may be confused into thinking (a || b) && c
if (a || b && c) {
  return d;
}

// good
const foo = (a && b < 0) || c > 0 || (d + 1 === 0);

// good
const bar = (a ** b) - (5 % d);

// good
if (a || (b && c)) {
  return d;
}

// good
const bar = a + b / c * d;
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Blocks 块</h2>

<a name="blocks--braces"></a><a name="16.1"></a>
  - <a href="#blocks--braces">16.1</a> Use braces with all multi-line blocks. eslint: <a href="https://eslint.org/docs/rules/nonblock-statement-body-position"><code>nonblock-statement-body-position</code></a>
    使用括号讲多行的块包裹起来

<pre><code>```javascript
// 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;
}
```
</code></pre>

<a name="blocks--cuddled-elses"></a><a name="16.2"></a>
  - <a href="#blocks--cuddled-elses">16.2</a> If you’re using multi-line blocks with <code>if</code> and <code>else</code>, put <code>else</code> on the same line as your <code>if</code> block’s closing brace. eslint: <a href="https://eslint.org/docs/rules/brace-style.html"><code>brace-style</code></a>
    如果你在if和else语句中使用了多行代码块,请将eles同样放在if闭合的括号旁边。

<pre><code>```javascript
// bad
if (test) {
  thing1();
  thing2();
}
else {
  thing3();
}

// good
if (test) {
  thing1();
  thing2();
} else {
  thing3();
}
```
</code></pre>

<a name="blocks--no-else-return"></a><a name="16.3"></a>
  - <a href="#blocks--no-else-return">16.3</a> If an <code>if</code> block always executes a <code>return</code> statement, the subsequent <code>else</code> block is unnecessary. A <code>return</code> in an <code>else if</code> block following an <code>if</code> block that contains a <code>return</code> can be separated into multiple <code>if</code> blocks. eslint: <a href="https://eslint.org/docs/rules/no-else-return"><code>no-else-return</code></a>
    如果一个if代码块总是有分开的return语句,随后的eles语句并不是必须的。如果一个包含 return 语句的 else if 块,在一个包含了 return 语句的 if 块之后,那么可以拆成多个 if 块。

<pre><code>```javascript
// bad
function foo() {
  if (x) {
    return x;
  } else {
    return y;
  }
}

// bad
function cats() {
  if (x) {
    return x;
  } else if (y) {
    return y;
  }
}

// bad
function dogs() {
  if (x) {
    return x;
  } else {
    if (y) {
      return y;
    }
  }
}

// good
function foo() {
  if (x) {
    return x;
  }

  return y;
}

// good
function cats() {
  if (x) {
    return x;
  }

  if (y) {
    return y;
  }
}

// good
function dogs(x) {
  if (x) {
    if (z) {
      return y;
    }
  } else {
    return z;
  }
}
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Control Statements (控制语句)</h2>

<a name="control-statements"></a>
  - <a href="#control-statements">17.1</a> In case your control statement (<code>if</code>, <code>while</code> etc.) gets too long or exceeds the maximum line length, each (grouped) condition could be put into a new line. The logical operator should begin the line.
    如果你的控制语句(if while等)太长或者超出最大的行宽,每一个条件语句可以分成新的一行,逻辑运算符必须放在行首。

<pre><code>> Why? Requiring operators at the beginning of the line keeps the operators aligned and follows a pattern similar to method chaining. This also improves readability by making it easier to visually follow complex logic.
> why? 在行头要求操作符保持对齐,并遵循类似的方法链模式,这样也提高了代码的可读性,并使其更容易的展示了复杂的逻辑。

```javascript
// bad
if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) {
  thing1();
}

// bad
if (foo === 123 &&
  bar === 'abc') {
  thing1();
}

// bad
if (foo === 123
  && bar === 'abc') {
  thing1();
}

// bad
if (
  foo === 123 &&
  bar === 'abc'
) {
  thing1();
}

// good
if (
  foo === 123
  && bar === 'abc'
) {
  thing1();
}

// good
if (
  (foo === 123 || bar === 'abc')
  && doesItLookGoodWhenItBecomesThatLong()
  && isThisReallyHappening()
) {
  thing1();
}

// good
if (foo === 123 && bar === 'abc') {
  thing1();
}
```
</code></pre>

<a name="control-statement--value-selection"></a>
  - <a href="#control-statements--value-selection">17.2</a> Don't use selection operators in place of control statements.
    不要用选择运算符来代替控制语句

<pre><code>```javascript
// bad
!isRunning && startRunning();

// good
if (!isRunning) {
  startRunning();
}
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Comments</h2>

<a name="comments--multiline"></a><a name="17.1"></a>
  - <a href="#comments--multiline">18.1</a> Use <code>/** ... */</code> for multi-line comments.
    使用<code>/** ... */</code>进行多行注释

<pre><code>```javascript
// 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;
}
```
</code></pre>

<a name="comments--singleline"></a><a name="17.2"></a>
  - <a href="#comments--singleline">18.2</a> Use <code>//</code> 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.
    使用<code>//</code>进行单行注释。请注释主题的上方放置新的一行注释。除非注释在块的第一行,不然前面空一行。

<pre><code>```javascript
// 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;
}
```
</code></pre>

<a name="comments--spaces"></a>
  - <a href="#comments--spaces">18.3</a> Start all comments with a space to make it easier to read. eslint: <a href="https://eslint.org/docs/rules/spaced-comment"><code>spaced-comment</code></a>
    在所有注释的前一行都空格,使其可读性更强。

<pre><code>```javascript
// 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;
}
```
</code></pre>

<a name="comments--actionitems"></a><a name="17.3"></a>
  - <a href="#comments--actionitems">18.4</a> Prefixing your comments with <code>FIXME</code> or <code>TODO</code> 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 <code>FIXME: -- need to figure this out</code> or <code>TODO: -- need to implement</code>.
    在注释前添加<code>FIXME</code>或者<code>TODO</code>去帮助开发人员更好地里面你是否需要重写这个问题,或者如果你建议需要实现一个解决该问题的方式。这些注释与常规的注释不同,因为他们是可操作的。

<a name="comments--fixme"></a><a name="17.4"></a>
  - <a href="#comments--fixme">18.5</a> Use <code>// FIXME:</code> to annotate problems.
    使用<code>// FIXME</code>去注释一个问题

<pre><code>```javascript
class Calculator extends Abacus {
  constructor() {
    super();

    // FIXME: shouldn’t use a global here
    total = 0;
  }
}
```
</code></pre>

<a name="comments--todo"></a><a name="17.5"></a>
  - <a href="#comments--todo">18.6</a> Use <code>// TODO:</code> to annotate solutions to problems.
    使用<code>// TODO</code>来注释一个问题的解决方法

<pre><code>```javascript
class Calculator extends Abacus {
  constructor() {
    super();

    // TODO: total should be configurable by an options param
    this.total = 0;
  }
}
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Whitespace</h2>

<a name="whitespace--spaces"></a><a name="18.1"></a>
  - <a href="#whitespace--spaces">19.1</a> Use soft tabs (space character) set to 2 spaces. eslint: <a href="https://eslint.org/docs/rules/indent.html"><code>indent</code></a>
    使用tab缩进设置成两个空格

<pre><code>```javascript
// bad
function foo() {
∙∙∙∙let name;
}

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

// good
function baz() {
∙∙let name;
}
```
</code></pre>

<a name="whitespace--before-blocks"></a><a name="18.2"></a>
  - <a href="#whitespace--before-blocks">19.2</a> Place 1 space before the leading brace. eslint: <a href="https://eslint.org/docs/rules/space-before-blocks.html"><code>space-before-blocks</code></a>
    在主体前放一个空格

<pre><code>```javascript
// 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',
});
```
</code></pre>

<a name="whitespace--around-keywords"></a><a name="18.3"></a>
  - <a href="#whitespace--around-keywords">19.3</a> Place 1 space before the opening parenthesis in control statements (<code>if</code>, <code>while</code> etc.). Place no space between the argument list and the function name in function calls and declarations. eslint: <a href="https://eslint.org/docs/rules/keyword-spacing.html"><code>keyword-spacing</code></a>
    在控制语句的括号前面放一个空格。在函数调用和声明之间,和参数列表和函数名之前不放空格。

<pre><code>```javascript
// bad
if(isJedi) {
  fight ();
}

// good
if (isJedi) {
  fight();
}

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

// good
function fight() {
  console.log('Swooosh!');
}
```
</code></pre>

<a name="whitespace--infix-ops"></a><a name="18.4"></a>
  - <a href="#whitespace--infix-ops">19.4</a> Set off operators with spaces. eslint: <a href="https://eslint.org/docs/rules/space-infix-ops.html"><code>space-infix-ops</code></a>
    用空格将运算符分开

<pre><code>```javascript
// bad
const x=y+5;

// good
const x = y + 5;
```
</code></pre>

<a name="whitespace--newline-at-end"></a><a name="18.5"></a>
  - <a href="#whitespace--newline-at-end">19.5</a> End files with a single newline character. eslint: <a href="https://github.com/eslint/eslint/blob/master/docs/rules/eol-last.md"><code>eol-last</code></a>
    在文件的结尾用新一个单独的回车换行符。

<pre><code>```javascript
// bad
import { es6 } from './AirbnbStyleGuide';
  // ...
export default es6;
```

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

```javascript
// good
import { es6 } from './AirbnbStyleGuide';
  // ...
export default es6;↵
```
</code></pre>

<a name="whitespace--chains"></a><a name="18.6"></a>
  - <a href="#whitespace--chains">19.6</a> 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: <a href="https://eslint.org/docs/rules/newline-per-chained-call"><code>newline-per-chained-call</code></a> <a href="https://eslint.org/docs/rules/no-whitespace-before-property"><code>no-whitespace-before-property</code></a>
    当书写长的链式函数(超过两个方法)时。在行首使用点号,这样可以强调这是一个函数方法调用而不是一个声明。

<pre><code>```javascript
// 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);
```
</code></pre>

<a name="whitespace--after-blocks"></a><a name="18.7"></a>
  - <a href="#whitespace--after-blocks">19.7</a> Leave a blank line after blocks and before the next statement.
    在每一个快之后和下一个声明之前空行

<pre><code>```javascript
// 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;
```
</code></pre>

<a name="whitespace--padded-blocks"></a><a name="18.8"></a>
  - <a href="#whitespace--padded-blocks">19.8</a> Do not pad your blocks with blank lines. eslint: <a href="https://eslint.org/docs/rules/padded-blocks.html"><code>padded-blocks</code></a>
    不要用空行填充块。

<pre><code>```javascript
// bad
function bar() {

  console.log(foo);

}

// bad
if (baz) {

  console.log(qux);
} else {
  console.log(foo);

}

// bad
class Foo {

  constructor(bar) {
    this.bar = bar;
  }
}

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

// good
if (baz) {
  console.log(qux);
} else {
  console.log(foo);
}
```
</code></pre>

<a name="whitespace--in-parens"></a><a name="18.9"></a>
  - <a href="#whitespace--in-parens">19.9</a> Do not add spaces inside parentheses. eslint: <a href="https://eslint.org/docs/rules/space-in-parens.html"><code>space-in-parens</code></a>
    不要在括号内添加空格

<pre><code>```javascript
// bad
function bar( foo ) {
  return foo;
}

// good
function bar(foo) {
  return foo;
}

// bad
if ( foo ) {
  console.log(foo);
}

// good
if (foo) {
  console.log(foo);
}
```
</code></pre>

<a name="whitespace--in-brackets"></a><a name="18.10"></a>
  - <a href="#whitespace--in-brackets">19.10</a> Do not add spaces inside brackets. eslint: <a href="https://eslint.org/docs/rules/array-bracket-spacing.html"><code>array-bracket-spacing</code></a>
    不要在大括号内侧添加空格

<pre><code>```javascript
// bad
const foo = [ 1, 2, 3 ];
console.log(foo[ 0 ]);

// good
const foo = [1, 2, 3];
console.log(foo[0]);
```
</code></pre>

<a name="whitespace--in-braces"></a><a name="18.11"></a>
  - <a href="#whitespace--in-braces">19.11</a> Add spaces inside curly braces. eslint: <a href="https://eslint.org/docs/rules/object-curly-spacing.html"><code>object-curly-spacing</code></a>
    在花括号的两侧添加空格

<pre><code>```javascript
// bad
const foo = {clark: 'kent'};

// good
const foo = { clark: 'kent' };
```
</code></pre>

<a name="whitespace--max-len"></a><a name="18.12"></a>
  - <a href="#whitespace--max-len">19.12</a> Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per <a href="#strings--line-length">above</a>, long strings are exempt from this rule, and should not be broken up. eslint: <a href="https://eslint.org/docs/rules/max-len.html"><code>max-len</code></a>
    避免一行代码超过100个字符(包括空格)。注意:根据以上规则,长字符串不受此规则约束,并且不应该被打断

<pre><code>> Why? This ensures readability and maintainability.
> why? 这样保证了可读性和可维护性

```javascript
// bad
const foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy;

// bad
$.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.'));

// good
const foo = jsonData
  && jsonData.foo
  && jsonData.foo.bar
  && jsonData.foo.bar.baz
  && jsonData.foo.bar.baz.quux
  && jsonData.foo.bar.baz.quux.xyzzy;

// good
$.ajax({
  method: 'POST',
  url: 'https://airbnb.com/',
  data: { name: 'John' },
})
  .done(() => console.log('Congratulations!'))
  .fail(() => console.log('You have failed this city.'));
```
</code></pre>

<a name="whitespace--block-spacing"></a>
  - <a href="#whitespace--block-spacing">19.13</a> Require consistent spacing inside an open block token and the next token on the same line. This rule also enforces consistent spacing inside a close block token and previous token on the same line. eslint: <a href="https://eslint.org/docs/rules/block-spacing"><code>block-spacing</code></a>
    代码块空格请保持一致

<pre><code>```javascript
// bad
function foo() {return true;}
if (foo) { bar = 0;}

// good
function foo() { return true; }
if (foo) { bar = 0; }
```
</code></pre>

<a name="whitespace--comma-spacing"></a>
  - <a href="#whitespace--comma-spacing">19.14</a> Avoid spaces before commas and require a space after commas. eslint: <a href="https://eslint.org/docs/rules/comma-spacing"><code>comma-spacing</code></a>
    不要在逗号前空格,在逗号后空格

<pre><code>```javascript
// bad
var foo = 1,bar = 2;
var arr = [1 , 2];

// good
var foo = 1, bar = 2;
var arr = [1, 2];
```
</code></pre>

<a name="whitespace--computed-property-spacing"></a>
  - <a href="#whitespace--computed-property-spacing">19.15</a> Enforce spacing inside of computed properties. eslint: <a href="https://eslint.org/docs/rules/computed-property-spacing"><code>computed-property-spacing</code></a>
    强制计算属性内使用空格

<pre><code>```javascript
// bad
obj[foo ]
obj[ 'foo']
var x = {[ b ]: a}
obj[foo[ bar ]]

// good
obj[foo]
obj['foo']
var x = { [b]: a }
obj[foo[bar]]
```
</code></pre>

<a name="whitespace--func-call-spacing"></a>
  - <a href="#whitespace--func-call-spacing">19.16</a> Avoid spaces between functions and their invocations. eslint: <a href="https://eslint.org/docs/rules/func-call-spacing"><code>func-call-spacing</code></a>
    避免函数调用直接的空格

<pre><code>```javascript
// bad
func ();

func
();

// good
func();
```
</code></pre>

<a name="whitespace--key-spacing"></a>
  - <a href="#whitespace--key-spacing">19.17</a> Enforce spacing between keys and values in object literal properties. eslint: <a href="https://eslint.org/docs/rules/key-spacing"><code>key-spacing</code></a>
    在对象文字属性中要求键和值之间的间隔。

<pre><code>```javascript
// bad
var obj = { "foo" : 42 };
var obj2 = { "foo":42 };

// good
var obj = { "foo": 42 };
```
</code></pre>

<a name="whitespace--no-trailing-spaces"></a>
  - <a href="#whitespace--no-trailing-spaces">19.18</a> Avoid trailing spaces at the end of lines. eslint: <a href="https://eslint.org/docs/rules/no-trailing-spaces"><code>no-trailing-spaces</code></a>
    避免行尾跟着空格

<a name="whitespace--no-multiple-empty-lines"></a>
  - <a href="#whitespace--no-multiple-empty-lines">19.19</a> Avoid multiple empty lines and only allow one newline at the end of files. eslint: <a href="https://eslint.org/docs/rules/no-multiple-empty-lines"><code>no-multiple-empty-lines</code></a>
    避免多个空行,并且只允许在文件末尾有一个换行符

<pre><code><!-- markdownlint-disable MD012 -->
```javascript
// bad
var x = 1;



var y = 2;

// good
var x = 1;

var y = 2;
```
<!-- markdownlint-enable MD012 -->
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Commas</h2>

<a name="commas--leading-trailing"></a><a name="19.1"></a>
  - <a href="#commas--leading-trailing">20.1</a> Leading commas: <strong>Nope.</strong> eslint: <a href="https://eslint.org/docs/rules/comma-style.html"><code>comma-style</code></a>
    不要把逗号写在行首

<pre><code>```javascript
// bad
const story = [
    once
  , upon
  , aTime
];

// good
const story = [
  once,
  upon,
  aTime,
];

// bad
const hero = {
    firstName: 'Ada'
  , lastName: 'Lovelace'
  , birthYear: 1815
  , superPower: 'computers'
};

// good
const hero = {
  firstName: 'Ada',
  lastName: 'Lovelace',
  birthYear: 1815,
  superPower: 'computers',
};
```
</code></pre>

<a name="commas--dangling"></a><a name="19.2"></a>
  - <a href="#commas--dangling">20.2</a> Additional trailing comma: <strong>Yup.</strong> eslint: <a href="https://eslint.org/docs/rules/comma-dangle.html"><code>comma-dangle</code></a>
    在尾部添加一个额外的逗号

<pre><code>> Why? This leads to cleaner git diffs. Also, transpilers like Babel will remove the additional trailing comma in the transpiled code which means you don’t have to worry about the [trailing comma problem](https://github.com/airbnb/javascript/blob/es5-deprecated/es5/README.md#commas) in legacy browsers.
> why?这可以是git diff更加的清晰。此外,像babel这样的预处理器会讲多余的逗号去除掉,所以不用担心老版本浏览器的解析问题

```diff
// bad - git diff without trailing comma
const hero = {
     firstName: 'Florence',
-    lastName: 'Nightingale'
+    lastName: 'Nightingale',
+    inventorOf: ['coxcomb chart', 'modern nursing']
};

// good - git diff with trailing comma
const hero = {
     firstName: 'Florence',
     lastName: 'Nightingale',
+    inventorOf: ['coxcomb chart', 'modern nursing'],
};
```

```javascript
// bad
const hero = {
  firstName: 'Dana',
  lastName: 'Scully'
};

const heroes = [
  'Batman',
  'Superman'
];

// good
const hero = {
  firstName: 'Dana',
  lastName: 'Scully',
};

const heroes = [
  'Batman',
  'Superman',
];

// bad
function createHero(
  firstName,
  lastName,
  inventorOf
) {
  // does nothing
}

// good
function createHero(
  firstName,
  lastName,
  inventorOf,
) {
  // does nothing
}

// good (note that a comma must not appear after a "rest" element)
function createHero(
  firstName,
  lastName,
  inventorOf,
  ...heroArgs
) {
  // does nothing
}

// bad
createHero(
  firstName,
  lastName,
  inventorOf
);

// good
createHero(
  firstName,
  lastName,
  inventorOf,
);

// good (note that a comma must not appear after a "rest" element)
createHero(
  firstName,
  lastName,
  inventorOf,
  ...heroArgs
);
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Semicolons</h2>

<a name="semicolons--required"></a><a name="20.1"></a>
  - <a href="#semicolons--required">21.1</a> <strong>Yup.</strong> eslint: <a href="https://eslint.org/docs/rules/semi.html"><code>semi</code></a>

<pre><code>> Why? When JavaScript encounters a line break without a semicolon, it uses a set of rules called [Automatic Semicolon Insertion](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion) to determine whether or not it should regard that line break as the end of a statement, and (as the name implies) place a semicolon into your code before the line break if it thinks so. ASI contains a few eccentric behaviors, though, and your code will break if JavaScript misinterprets your line break. These rules will become more complicated as new features become a part of JavaScript. Explicitly terminating your statements and configuring your linter to catch missing semicolons will help prevent you from encountering issues.
> why? 当 JavaScript 遇见一个没有分号的换行符时,它会使用一个叫做 Automatic Semicolon Insertion 的规则来确定是否应该以换行符视为语句的结束,并且如果认为如此,会在代码中断前插入一个分号到代码中。 但是,ASI 包含了一些奇怪的行为,如果 JavaScript 错误的解释了你的换行符,你的代码将会中断。 随着新特性成为 JavaScript 的一部分,这些规则将变得更加复杂。 明确地终止你的语句,并配置你的 linter 以捕获缺少的分号将有助于防止你遇到的问题。

```javascript
// bad - raises exception
const luke = {}
const leia = {}
[luke, leia].forEach(jedi => jedi.father = 'vader')

// bad - raises exception
const reaction = "No! That’s impossible!"
(async function meanwhileOnTheFalcon() {
  // handle `leia`, `lando`, `chewie`, `r2`, `c3p0`
  // ...
}())

// bad - returns `undefined` instead of the value on the next line - always happens when `return` is on a line by itself because of ASI!
function foo() {
  return
    'search your feelings, you know it to be foo'
}

// good
const luke = {};
const leia = {};
[luke, leia].forEach((jedi) => {
  jedi.father = 'vader';
});

// good
const reaction = "No! That’s impossible!";
(async function meanwhileOnTheFalcon() {
  // handle `leia`, `lando`, `chewie`, `r2`, `c3p0`
  // ...
}());

// good
function foo() {
  return 'search your feelings, you know it to be foo';
}
```

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

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Type Casting & Coercion (类型转换和强制类型转换)</h2>

<a name="coercion--explicit"></a><a name="21.1"></a>
  - <a href="#coercion--explicit">22.1</a> Perform type coercion at the beginning of the statement.
    在语句的开始部分进行类型转换

<a name="coercion--strings"></a><a name="21.2"></a>
  - <a href="#coercion--strings">22.2</a>  Strings: eslint: <a href="https://eslint.org/docs/rules/no-new-wrappers"><code>no-new-wrappers</code></a>

<pre><code>```javascript
// => this.reviewScore = 9;

// bad
const totalScore = new String(this.reviewScore); // typeof totalScore is "object" not "string"

// bad
const totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf()

// bad
const totalScore = this.reviewScore.toString(); // isn’t guaranteed to return a string

// good
const totalScore = String(this.reviewScore);
```
</code></pre>

<a name="coercion--numbers"></a><a name="21.3"></a>
  - <a href="#coercion--numbers">22.3</a> Numbers: Use <code>Number</code> for type casting and <code>parseInt</code> always with a radix for parsing strings. eslint: <a href="https://eslint.org/docs/rules/radix"><code>radix</code></a> <a href="https://eslint.org/docs/rules/no-new-wrappers"><code>no-new-wrappers</code></a>
    使用Number进行类型转换,转化字符串的时候用带基数的parseInt

<pre><code>```javascript
const inputValue = '4';

// bad
const val = new Number(inputValue);

// bad
const val = +inputValue;

// bad
const val = inputValue >> 0;

// bad
const val = parseInt(inputValue);

// good
const val = Number(inputValue);

// good
const val = parseInt(inputValue, 10);
```
</code></pre>

<a name="coercion--comment-deviations"></a><a name="21.4"></a>
  - <a href="#coercion--comment-deviations">22.4</a> If for whatever reason you are doing something wild and <code>parseInt</code> is your bottleneck and need to use Bitshift for <a href="https://jsperf.com/coercion-vs-casting/3">performance reasons</a>, leave a comment explaining why and what you’re doing.
    如果你一定要使用这种bitshift,请留下注释,你为什么要这么做。

<pre><code>```javascript
// good
/**
 * parseInt was the reason my code was slow.
 * Bitshifting the String to coerce it to a
 * Number made it a lot faster.
 */
const val = inputValue >> 0;
```
</code></pre>

<a name="coercion--bitwise"></a><a name="21.5"></a>
  - <a href="#coercion--bitwise">22.5</a> <strong>Note:</strong> Be careful when using bitshift operations. Numbers are represented as <a href="https://es5.github.io/#x4.3.19">64-bit values</a>, but bitshift operations always return a 32-bit integer (<a href="https://es5.github.io/#x11.7">source</a>). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. <a href="https://github.com/airbnb/javascript/issues/109">Discussion</a>. Largest signed 32-bit Int is 2,147,483,647:
    注意:当你使用位运算的时候要小心。 数字总是被以 64-bit 值 的形式表示,但是位运算总是返回一个 32-bit 的整数 (来源)。 对于大于 32 位的整数值,位运算可能会导致意外行为。讨论。 最大的 32 位整数是: 2,147,483,647。

<pre><code>```javascript
2147483647 >> 0; // => 2147483647
2147483648 >> 0; // => -2147483648
2147483649 >> 0; // => -2147483647
```
</code></pre>

<a name="coercion--booleans"></a><a name="21.6"></a>
  - <a href="#coercion--booleans">22.6</a> Booleans: eslint: <a href="https://eslint.org/docs/rules/no-new-wrappers"><code>no-new-wrappers</code></a>

<pre><code>```javascript
const age = 0;

// bad
const hasAge = new Boolean(age);

// good
const hasAge = Boolean(age);

// best
const hasAge = !!age;
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Naming Conventions(命名规则)</h2>

<a name="naming--descriptive"></a><a name="22.1"></a>
  - <a href="#naming--descriptive">23.1</a> Avoid single letter names. Be descriptive with your naming. eslint: <a href="https://eslint.org/docs/rules/id-length"><code>id-length</code></a>
    避免单个字符的命名

<pre><code>```javascript
// bad
function q() {
  // ...
}

// good
function query() {
  // ...
}
```
</code></pre>

<a name="naming--camelCase"></a><a name="22.2"></a>
  - <a href="#naming--camelCase">23.2</a> Use camelCase when naming objects, functions, and instances. eslint: <a href="https://eslint.org/docs/rules/camelcase.html"><code>camelcase</code></a>
    使用驼峰命名对象,函数和实例。

<pre><code>```javascript
// bad
const OBJEcttsssss = {};
const this_is_my_object = {};
function c() {}

// good
const thisIsMyObject = {};
function thisIsMyFunction() {}
```
</code></pre>

<a name="naming--PascalCase"></a><a name="22.3"></a>
  - <a href="#naming--PascalCase">23.3</a> Use PascalCase only when naming constructors or classes. eslint: <a href="https://eslint.org/docs/rules/new-cap.html"><code>new-cap</code></a>
    当命名构造器和类的时候,使用PascalCase

<pre><code>```javascript
// bad
function user(options) {
  this.name = options.name;
}

const bad = new user({
  name: 'nope',
});

// good
class User {
  constructor(options) {
    this.name = options.name;
  }
}

const good = new User({
  name: 'yup',
});
```
</code></pre>

<a name="naming--leading-underscore"></a><a name="22.4"></a>
  - <a href="#naming--leading-underscore">23.4</a> Do not use trailing or leading underscores. eslint: <a href="https://eslint.org/docs/rules/no-underscore-dangle.html"><code>no-underscore-dangle</code></a>
    不要在命名前后使用下划线

<pre><code>> Why? JavaScript does not have the concept of privacy in terms of properties or methods. Although a leading underscore is a common convention to mean “private”, in fact, these properties are fully public, and as such, are part of your public API contract. This convention might lead developers to wrongly think that a change won’t count as breaking, or that tests aren’t needed. tl;dr: if you want something to be “private”, it must not be observably present.

```javascript
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
this._firstName = 'Panda';

// good
this.firstName = 'Panda';

// good, in environments where WeakMaps are available
// see https://kangax.github.io/compat-table/es6/#test-WeakMap
const firstNames = new WeakMap();
firstNames.set(this, 'Panda');
```
</code></pre>

<a name="naming--self-this"></a><a name="22.5"></a>
  - <a href="#naming--self-this">23.5</a> Don’t save references to <code>this</code>. Use arrow functions or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">Function#bind</a>.
    不要保存<code>this</code>的引用

<pre><code>```javascript
// bad
function foo() {
  const self = this;
  return function () {
    console.log(self);
  };
}

// bad
function foo() {
  const that = this;
  return function () {
    console.log(that);
  };
}

// good
function foo() {
  return () => {
    console.log(this);
  };
}
```
</code></pre>

<a name="naming--filename-matches-export"></a><a name="22.6"></a>
  - <a href="#naming--filename-matches-export">23.6</a> A base filename should exactly match the name of its default export.
    一个基本的文件名需要与其默认导出的名称完全匹配。

<pre><code>```javascript
// file 1 contents
class CheckBox {
  // ...
}
export default CheckBox;

// file 2 contents
export default function fortyTwo() { return 42; }

// file 3 contents
export default function insideDirectory() {}

// in some other file
// bad
import CheckBox from './checkBox'; // PascalCase import/export, camelCase filename
import FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase export
import InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export

// bad
import CheckBox from './check_box'; // PascalCase import/export, snake_case filename
import forty_two from './forty_two'; // snake_case import/filename, camelCase export
import inside_directory from './inside_directory'; // snake_case import, camelCase export
import index from './inside_directory/index'; // requiring the index file explicitly
import insideDirectory from './insideDirectory/index'; // requiring the index file explicitly

// good
import CheckBox from './CheckBox'; // PascalCase export/import/filename
import fortyTwo from './fortyTwo'; // camelCase export/import/filename
import insideDirectory from './insideDirectory'; // camelCase export/import/directory name/implicit "index"
// ^ supports both insideDirectory.js and insideDirectory/index.js
```
</code></pre>

<a name="naming--camelCase-default-export"></a><a name="22.7"></a>
  - <a href="#naming--camelCase-default-export">23.7</a> Use camelCase when you export-default a function. Your filename should be identical to your function’s name.
    当你导出一个默认函数时使用驼峰的方式。你的文件名应该和你的函数名一致。

<pre><code>```javascript
function makeStyleGuide() {
  // ...
}

export default makeStyleGuide;
```
</code></pre>

<a name="naming--PascalCase-singleton"></a><a name="22.8"></a>
  - <a href="#naming--PascalCase-singleton">23.8</a> Use PascalCase when you export a constructor / class / singleton / function library / bare object.
    何时使用帕斯卡命名,当你导出构造器,类,单例,函数库,空对象时。

<pre><code>```javascript
const AirbnbStyleGuide = {
  es6: {
  },
};

export default AirbnbStyleGuide;
```
</code></pre>

<a name="naming--Acronyms-and-Initialisms"></a>
  - <a href="#naming--Acronyms-and-Initialisms">23.9</a> Acronyms and initialisms should always be all capitalized, or all lowercased.
    首字母缩写的词应该都为大写或者都为小写

<pre><code>> Why? Names are for readability, not to appease a computer algorithm.
> why? 名字是为了可读性,不是为了满足计算机的算法。

```javascript
// bad
import SmsContainer from './containers/SmsContainer';

// bad
const HttpRequests = [
  // ...
];

// good
import SMSContainer from './containers/SMSContainer';

// good
const HTTPRequests = [
  // ...
];

// also good
const httpRequests = [
  // ...
];

// best
import TextMessageContainer from './containers/TextMessageContainer';

// best
const requests = [
  // ...
];
```


- 23.10 You may optionally uppercase a constant only if it (1) is exported, (2) is a const (it can not be reassigned), and (3) the programmer can trust it (and its nested properties) to never change.
只有一个常量(1)被导出,(2)不能被修改,(3)程序员可以信任它不会被改变时,才可以使用大写字母表示。

> Why? This is an additional tool to assist in situations where the programmer would be unsure if a variable might ever change. UPPERCASE_VARIABLES are letting the programmer know that they can trust the variable (and its properties) not to change.
> why? 当时程序员不确定这个变量是否会被改变时,这是一种辅助工具帮助判断。
- What about all `const` variables? - This is unnecessary, so uppercasing should not be used for constants within a file. It should be used for exported constants however.
- 是否需要用于所有的常量变量? 这是不必须要的,在一个文件内命名行常量时不需要,但是当作为一个导出常量时需要。
- What about exported objects? - Uppercase at the top level of export  (e.g. `EXPORTED_OBJECT.key`) and maintain that all nested properties do not change.
- 导出的对象是否需要?在导出的顶层使用,并保持所有的嵌套属性不变的情况下。

```javascript
// bad
const PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file';

// bad
export const THING_TO_BE_CHANGED = 'should obviously not be uppercased';

// bad
export let REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables';

// ---

// allowed but does not supply semantic value
export const apiKey = 'SOMEKEY';

// better in most cases
export const API_KEY = 'SOMEKEY';

// ---

// bad - unnecessarily uppercases key while adding no semantic value
export const MAPPING = {
  KEY: 'value'
};

// good
export const MAPPING = {
  key: 'value'
};
```

⬆ back to top

Accessors (存储器)


- 24.1 Accessor functions for properties are not required.
对属性的存储器是不被需要恶毒


- 24.2 Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use getVal() and setVal('hello').
不要使用 JavaScript 的 getters/setters 方法,因为它们会导致意外的副作用,并且更加难以测试、维护和推敲。 相应的,如果你需要存取函数的时候使用 getVal() 和 setVal('hello')。

```javascript
// bad
class Dragon {
  get age() {
    // ...
  }

  set age(value) {
    // ...
  }
}

// good
class Dragon {
  getAge() {
    // ...
  }

  setAge(value) {
    // ...
  }
}
```
</code></pre>

<a name="accessors--boolean-prefix"></a><a name="23.3"></a>
  - <a href="#accessors--boolean-prefix">24.3</a> If the property/method is a <code>boolean</code>, use <code>isVal()</code> or <code>hasVal()</code>.
    如果属性名或方法返回的是布尔值,使用<code>isVal()</code> or <code>hasVal()</code>.

<pre><code>```javascript
// bad
if (!dragon.age()) {
  return false;
}

// good
if (!dragon.hasAge()) {
  return false;
}
```
</code></pre>

<a name="accessors--consistent"></a><a name="23.4"></a>
  - <a href="#accessors--consistent">24.4</a> It’s okay to create <code>get()</code> and <code>set()</code> functions, but be consistent.
  如果要创建get()和set()函数,请保持一致性

<pre><code>```javascript
class Jedi {
  constructor(options = {}) {
    const lightsaber = options.lightsaber || 'blue';
    this.set('lightsaber', lightsaber);
  }

  set(key, val) {
    this[key] = val;
  }

  get(key) {
    return this[key];
  }
}
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>Events (事件)</h2>

<a name="events--hash"></a><a name="24.1"></a>
  - <a href="#events--hash">25.1</a> When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass an object literal (also known as a "hash")  instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:
    当给事件附加数据时(无论是DOM事件还是更加私有的事件,传递一个对象而不是原始值。这样可以让后续的开发者更有效给这个事件添加数据,而不需要找到并更新这个事件的所有事件。

<pre><code>```javascript
// bad
$(this).trigger('listingUpdated', listing.id);

// ...

$(this).on('listingUpdated', (e, listingID) => {
  // do something with listingID
});
```

prefer:

```javascript
// good
$(this).trigger('listingUpdated', { listingID: listing.id });

// ...

$(this).on('listingUpdated', (e, data) => {
  // do something with data.listingID
});
```
</code></pre>

<strong><a href="#table-of-contents">⬆ back to top</a></strong>

<h2>jQuery</h2>

<a name="jquery--dollar-prefix"></a><a name="25.1"></a>
  - <a href="#jquery--dollar-prefix">26.1</a> Prefix jQuery object variables with a <code>$</code>.
    在JQuery对象的声明加上<code>$</code>的前缀

<pre><code>```javascript
// bad
const sidebar = $('.sidebar');

// good
const $sidebar = $('.sidebar');

// good
const $sidebarBtn = $('.sidebar-btn');
```
</code></pre>

<a name="jquery--cache"></a><a name="25.2"></a>
  - <a href="#jquery--cache">26.2</a> Cache jQuery lookups.
    缓存JQuery的查询对象。

<pre><code>```javascript
// bad
function setSidebar() {
  $('.sidebar').hide();

  // ...

  $('.sidebar').css({
    'background-color': 'pink',
  });
}

// good
function setSidebar() {
  const $sidebar = $('.sidebar');
  $sidebar.hide();

  // ...

  $sidebar.css({
    'background-color': 'pink',
  });
}
```
</code></pre>

<a name="jquery--queries"></a><a name="25.3"></a>
  - <a href="#jquery--queries">26.3</a> For DOM queries use Cascading <code>$('.sidebar ul')</code> or parent > child <code>$('.sidebar > ul')</code>. <a href="http://jsperf.com/jquery-find-vs-context-sel/16">jsPerf</a>
  在DOM查询中使用串联的查询方式<code>$('.sidebar ul')</code>或者父 > 子<code>$('.sidebar > ul')</code>

<a name="jquery--find"></a><a name="25.4"></a>
  - <a href="#jquery--find">26.4</a> Use <code>find</code> with scoped jQuery object queries.
    基于JQuery的对象作用域使用find方法

<pre><code>```javascript
// bad
$('ul', '.sidebar').hide();

// bad
$('.sidebar').find('ul').hide();

// good
$('.sidebar ul').hide();

// good
$('.sidebar > ul').hide();

// good
$sidebar.find('ul').hide();
```

⬆ back to top

ECMAScript 5 Compatibility


- 27.1 Refer to Kangax’s ES5 compatibility table.
- ECMAScript5的兼容性参考以上链接

⬆ back to top

ECMAScript 6+ (ES 2015+) Styles


- 28.1 This is a collection of links to the various ES6+ features.
- 这是一个链接ES6+特性的合集

  1. Arrow Functions箭头函数
  2. Classes
  3. Object Shorthand对象简写
  4. Object Concise对象简洁
  5. Object Computed Properties对象计算属性
  6. Template Strings模版字符串
  7. Destructuring解构
  8. Default Parameters默认参数
  9. Restrest运算符
  10. Array Spreads数组扩展
  11. Let and Constlet和const
  12. Exponentiation Operator取幂运算符
  13. Iterators and Generators迭代器和生成器
  14. Modules模块

    • 28.2 Do not use TC39 proposals that have not reached stage 3.
      不要使用尚未达到第3阶段的 TC39 建议。

    Why? They are not finalized, and they are subject to change or to be withdrawn entirely. We want to use JavaScript, and proposals are not JavaScript yet.

⬆ back to top

Standard Library (标准库)

The Standard Library
contains utilities that are functionally broken but remain for legacy reasons.
标准库包含的一些实用方法在功能上有缺陷,但是由于历史遗留原因仍然存在。


- 29.1 Use Number.isNaN instead of global isNaN.
eslint: no-restricted-globals
使用Number.isNan来代替全局的isNaN

> Why? The global `isNaN` coerces non-numbers to numbers, returning true for anything that coerces to NaN.
> why? 全局的isNaN强制转换非数字类型的为数组类型,对任何强制转换为NaN的东西都返回true
> If this behavior is desired, make it explicit.
>如果你需要这种行为,请注明

```javascript
// bad
isNaN('1.2'); // false
isNaN('1.2.3'); // true

// good
Number.isNaN('1.2.3'); // false
Number.isNaN(Number('1.2.3')); // true
```


- 29.2 Use Number.isFinite instead of global isFinite.
eslint: no-restricted-globals

> Why? The global `isFinite` coerces non-numbers to numbers, returning true for anything that coerces to a finite number.
> why? 全局的 isFinite 强制非数字转化为数字,对任何强制转化为有限数字的东西都返回 true。
> If this behavior is desired, make it explicit.
> 如使用请注明。

```javascript
// bad
isFinite('2e3'); // true

// good
Number.isFinite('2e3'); // false
Number.isFinite(parseInt('2e3', 10)); // true
```

⬆ back to top

Testing (测试)


- 30.1 Yup.

```javascript
function foo() {
  return true;
}
```


- 30.2 No, but seriously:
- 没有,但是认真的
- Whichever testing framework you use, you should be writing tests! 无论你使用哪种测试框架,你都需要编写测试
- Strive to write many small pure functions, and minimize where mutations occur. 努力编写尽量小尽量纯净的函数,并减少发生突变的地方。
- Be cautious about stubs and mocks - they can make your tests more brittle. 对于静态方法和mock需要小心,它会使你的测试变弱。
- We primarily use mocha and jest at Airbnb. tape is also used occasionally for small, separate modules.我们在airbnb使用mocha和jest。tape也偶尔被运用在一些小的,分离开的模块。
- 100% test coverage is a good goal to strive for, even if it’s not always practical to reach it. 100%的测试覆盖率是一个值得努力的目标,即使它并不是很好达到。
- Whenever you fix a bug, write a regression test. A bug fixed without a regression test is almost certainly going to break again in the future.无论何时修复bug,都要编写一个回归测试。在没有回归测试的情况下修复的bug在将来几乎肯定会再次崩溃。

⬆ back to top

Performance (性能)

⬆ back to top

Resources (资源)

Learning ES6+

Read This

Tools

Other Style Guides

Other Styles

Further Reading

Books

Blogs

Podcasts

⬆ back to top

In the Wild

This is a list of organizations that are using this style guide. Send us a pull request and we'll add you to the list.

⬆ back to top

Translation

This style guide is also available in other languages:

The JavaScript Style Guide Guide

Chat With Us About JavaScript

Contributors

License

(The MIT License)

Copyright (c) 2018 linxiaohui

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

⬆ back to top

Amendments

We encourage you to fork this guide and change the rules to fit your team’s style guide. Below, you may list some amendments to the style guide. This allows you to periodically update your style guide without having to deal with merge conflicts.

};

看完两件小事

如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙:

  1. 关注我们的 GitHub 博客,让我们成为长期关系
  2. 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长!
  3. 关注公众号 「画漫画的程序员」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程

JS中文网是中国领先的新一代开发者社区和专业的技术媒体,一个帮助开发者成长的社区,目前已经覆盖和服务了超过 300 万开发者,你每天都可以在这里找到技术世界的头条内容。欢迎热爱技术的你一起加入交流与学习,JS中文网的使命是帮助开发者用代码改变世界

本文著作权归作者所有,如若转载,请注明出处

转载请注明:文章转载自「 Js中文网 · 前端进阶资源教程 」https://www.javascriptc.com

标题:javascript代码规范,应该这样写

链接:https://www.javascriptc.com/3139.html

« 复习20 个棘手的ES6面试问题来巩固自己JS基础
汇总ECMAScript 2016、2017、2018中所有新特性»
Flutter 中文教程资源

相关推荐

QR code