# Airbnb JavaScript Style Guide()
A mostly reasonable approach to JavaScript 一种写JavaScript更合理的代码风格。
Note: this guide assumes you are using Babel (opens new window), and requires that you use babel-preset-airbnb (opens new window) or the equivalent. It also assumes you are installing shims/polyfills in your app, with airbnb-browser-shims (opens new window) or the equivalent. 注意:本指南假定你正在使用Babel (opens new window)并要求你使用babel-preset-airbnb (opens new window)或者其他相同的资源。并且假定你在你的应用中安装了shims/polyfills,使用airbnb-browser-shims (opens new window)或相同的功能
# Table of Contents
- Types(类型)
- References(引用)
- Objects(对象)
- Arrays(数组)
- Destructuring(解构)
- Strings(字符串)
- Functions(函数)
- Arrow Functions(箭头函数)
- Classes & Constructors(类和构造器)
- Modules(模块)
- Iterators and Generators(迭代器和生成器)
- Properties(属性)
- Variables(变量)
- Hoisting(提升)
- Comparison Operators & Equality(比较运算符和等号)
- Blocks(块)
- Control Statements(控制语句)
- Comments(注释)
- Whitespace(空白)
- Commas(逗号)
- Semicolons(分号)
- Type Casting & Coercion(类型转换和强制类型转换)
- Naming Conventions(命名规则)
- Accessors(存储器)
- Events(事件)
- jQuery
- ECMAScript 5 Compatibility
- ECMAScript 6+ (ES 2015+) Styles
- Standard Library(标准库)
- Testing(测试)
- Performance(性能)
- Resources(资源)
# Types
1.1 Primitives: When you access a primitive type you work directly on its value. 原始值:当你访问一个原始类型的时候,你可以直接使用它的值
string
number
boolean
null
undefined
symbol
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
const foo = [1, 2]; const bar = foo; bar[0] = 9; console.log(foo[0], bar[0]); // => 9, 9
# References
2.1 Use
const
for all of your references; avoid usingvar
. eslint:prefer-const
(opens new window),no-const-assign
(opens new window) 使用const
进行复制,避免使用var。eslint:prefer-const
(opens new window),no-const-assign
(opens new window)Why? This ensures that you can’t reassign your references, which can lead to bugs and difficult to comprehend code. why?这样能够确保不能修改你的引用,否则会导致bug或者难以理解的错误
// bad var a = 1; var b = 2; // good const a = 1; const b = 2;
2.2 If you must reassign references, use
let
instead ofvar
. eslint:no-var
(opens new window) 如果你一定需要对应用重新赋值,使用let
来代替var
Why?
let
is block-scoped rather than function-scoped likevar
. why?let
是块级作用域而不是像var
的函数作用域// bad var count = 1; if (true) { count += 1; } // good, use the let. let count = 1; if (true) { count += 1; }
2.3 Note that both
let
andconst
are block-scoped. 注意:let
和const
都是块级作用域// const and let only exist in the blocks they are defined in. { let a = 1; const b = 1; } console.log(a); // ReferenceError console.log(b); // ReferenceError
# Objects
3.1 Use the literal syntax for object creation. eslint:
no-new-object
(opens new window) 使用字面量语法来创建对象eslint:no-new-object
(opens new window)// bad const item = new Object(); // good const item = {};
3.2 Use computed property names when creating objects with dynamic property names. 在使用动态属性名来创建对象时使用计算属性名
Why? They allow you to define all the properties of an object in one place. why?这样允许你在一个地方定义所有的属性名
function getKey(k) { return `a key named ${k}`; } // bad const obj = { id: 5, name: 'San Francisco', }; obj[getKey('enabled')] = true; // good const obj = { id: 5, name: 'San Francisco', [getKey('enabled')]: true, };
3.3 Use object method shorthand. eslint:
object-shorthand
(opens new window) 使用对象方法的简写eslint:object-shorthand
(opens new window)// bad const atom = { value: 1, addValue: function (value) { return atom.value + value; }, }; // good const atom = { value: 1, addValue(value) { return atom.value + value; }, };
3.4 Use property value shorthand. eslint:
object-shorthand
(opens new window) 使用属性值的简写Why? It is shorter to write and descriptive. why?这可以使其写法和描述更短
const lukeSkywalker = 'Luke Skywalker'; // bad const obj = { lukeSkywalker: lukeSkywalker, }; // good const obj = { lukeSkywalker, };
3.5 Group your shorthand properties at the beginning of your object declaration. 在最初声明对象的时候将你的简写属性进行分组
Why? It’s easier to tell which properties are using the shorthand. why?这样更容易知道那些属性是用了简写
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, };
3.6 Only quote properties that are invalid identifiers. eslint:
quote-props
(opens new window) 只使用引号标注无效标识符的属性eslint:quote-props
(opens new window)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引擎的优化
// 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 ashasOwnProperty
,propertyIsEnumerable
, andisPrototypeOf
. eslint:no-prototype-builtins
(opens new window) 不要直接调用Object.prototype方法,例如shasOwnProperty
,propertyIsEnumerable
和isPrototypeOf
. eslint:no-prototype-builtins
(opens new window)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
// 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
(opens new window) to shallow-copy objects. Use the object rest operator to get a new object with certain properties omitted. 更推荐使用拓展运动符而不是[Object.assign
]去浅拷贝一个对象。使用对象的rest运算符去获得一个确定没有被遗漏属性的对象// 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 }
# Arrays
4.1 Use the literal syntax for array creation. eslint:
no-array-constructor
(opens new window) 使用字面量去声明一个数组// bad const items = new Array(); // good const items = [];
4.2 Use Array#push (opens new window) instead of direct assignment to add items to an array. 使用Array#push (opens new window) 代替直接给数组添加项
const someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
4.3 Use array spreads
...
to copy arrays. 使用数组的展开方法...来拷贝数组// bad const len = items.length; const itemsCopy = []; let i; for (i = 0; i < len; i += 1) { itemsCopy[i] = items[i]; } // good const itemsCopy = [...items];
4.4 To convert an iterable object to an array, use spreads
...
instead ofArray.from
(opens new window). 将一个类数组对象转换成数组,使用展开方法...代替Array.from
(opens new window).const foo = document.querySelectorAll('.foo'); // good const nodes = Array.from(foo); // best const nodes = [...foo];
4.5 Use
Array.from
(opens new window) for converting an array-like object to an array. 使用Array.from
(opens new window)去转换一个类数组对象变成一个数组const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 }; // bad const arr = Array.prototype.slice.call(arrLike); // good const arr = Array.from(arrLike);
4.6 Use
Array.from
(opens new window) instead of spread...
for mapping over iterables, because it avoids creating an intermediate array. 使用Array.from
(opens new window)代替数组展开方法去循环一个可迭代的对象,因为这可以避免产生一个中间数组// bad const baz = [...foo].map(bar); // good const baz = Array.from(foo, bar);
4.7 Use return statements in array method callbacks. It’s ok to omit the return if the function body consists of a single statement returning an expression without side effects, following 8.2. eslint:
array-callback-return
(opens new window) 在数组方法的回调方法中使用return语句,如果函数体由一个不返回副作用的单个语句组成,那么可以考虑省略掉return语句。eslint:array-callback-return
(opens new window)// 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; });
4.8 Use line breaks after open and before close array brackets if an array has multiple lines 当数组有多行时,在数组开始和结尾的地方换行
// bad const arr = [ [0, 1], [2, 3], [4, 5], ]; const objectInArray = [{ id: 1, }, { id: 2, }]; const numberInArray = [ 1, 2, ]; // good const arr = [[0, 1], [2, 3], [4, 5]]; const objectInArray = [ { id: 1, }, { id: 2, }, ]; const numberInArray = [ 1, 2, ];
# Destructuring(解构)
5.1 Use object destructuring when accessing and using multiple properties of an object. eslint:
prefer-destructuring
(opens new window) 当从一个对象接受和使用多个属性的时候,使用对象额解构Why? Destructuring saves you from creating temporary references for those properties. why? 解构可以减少你为这个属性创建临时的引用
// 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}`; }
5.2 Use array destructuring. eslint:
prefer-destructuring
(opens new window) 使用数组的解构 eslint:prefer-destructuring
(opens new window)const arr = [1, 2, 3, 4]; // bad const first = arr[0]; const second = arr[1]; // good const [first, second] = arr;
5.3 Use object destructuring for multiple return values, not array destructuring. 当返回多个值时,使用对象的解构,而不是数组的解构
Why? You can add new properties over time or change the order of things without breaking call sites. why? 你可以添加或改变返回属性额度顺序,而不需要修改调用的地方。
// bad function processInput(input) { // then a miracle occurs return [left, right, top, bottom]; } // the caller needs to think about the order of return data // 调用的地方需要考虑返回数据的顺序 const [left, __, top] = processInput(input); // good function processInput(input) { // then a miracle occurs return { left, right, top, bottom }; } // the caller selects only the data they need // 使用对象解构,只用考虑所需要的返回值即可 const { left, top } = processInput(input);
# Strings
6.1 Use single quotes
''
for strings. eslint:quotes
(opens new window) 对字符串使用单引号// bad const name = "Capt. Janeway"; // bad - template literals should contain interpolation or newlines // 模板字符串需要包含变量或者新的一行 const name = `Capt. Janeway`; // good const name = 'Capt. Janeway';
6.2 Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation. 使行超过100个字符的字符串不应使用字符串连接跨多行写入。
Why? Broken strings are painful to work with and make code less searchable.
// bad const errorMessage = 'This is a super long error that was thrown because \ of Batman. When you stop to think about how Batman had anything to do \ with this, you would get nowhere \ fast.'; // bad const errorMessage = 'This is a super long error that was thrown because ' + 'of Batman. When you stop to think about how Batman had anything to do ' + 'with this, you would get nowhere fast.'; // good const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
6.3 When programmatically building up strings, use template strings instead of concatenation. eslint:
prefer-template
(opens new window)template-curly-spacing
(opens new window) 当使用编程模式创建字符串,使用模板字符串代替拼接。Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation . why? 模板字符串可以给你可读性更强,更简洁的代码,具有合适的换行和特征插值。
// bad function sayHi(name) { return 'How are you, ' + name + '?'; } // bad function sayHi(name) { return ['How are you, ', name, '?'].join(); } // bad function sayHi(name) { return `How are you, ${ name }?`; } // good function sayHi(name) { return `How are you, ${name}?`; }
- 6.4 Never use
eval()
on a string, it opens too many vulnerabilities. eslint:no-eval
(opens new window) 千万不要对字符串使用eval()
,这会导致太多问题。eslint:no-eval
(opens new window)
6.5 Do not unnecessarily escape characters in strings. eslint:
no-useless-escape
(opens new window) 不要转义没有必要的字符Why? Backslashes harm readability, thus they should only be present when necessary. why? 反斜杠难以阅读,只有在必须的时候再使用它们
// bad const foo = '\'this\' \i\s \"quoted\"'; // good const foo = '\'this\' is "quoted"'; const foo = `my name is '${name}'`;
# Functions
7.1 Use named function expressions instead of function declarations. eslint:
func-style
(opens new window) 使用命名的函数表达式代替函数命名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 (opens new window)) why? 函数声明会被提升,这意味着这非常容易在这个函数被声明之前去调用它。这会使代码可读性变差和难以维护。如果你发现一个函数的定义已经大和复杂的影响到对剩余文件的理解。那么是时候将它们提取到自己的模块中。不要忘了明确地给这个函数命名,不管它的名字中是否含有变量(在现代浏览器中经常是这样,或者在使用诸如Babel之类的编译器时)。这消除了对错误的调用堆栈的任何假设。
// bad function foo() { // ... } // bad const foo = function () { // ... }; // good // lexical name distinguished from the variable-referenced invocation(s) const short = function longUniqueMoreDescriptiveLexicalFoo() { // ... };
7.2 Wrap immediately invoked function expressions in parentheses. eslint:
wrap-iife
(opens new window) 将立即执行函数用圆括号包裹起来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 。
// immediately-invoked function expression (IIFE) (function () { console.log('Welcome to the Internet. Please follow me.'); }());
- 7.3 Never declare a function in a non-function block (
if
,while
, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears. eslint:no-loop-func
(opens new window) 切记不要在非功能块中声明函数 (if, while, 等)。 将函数赋值给变量。 浏览器允许你这样做,但是他们都有不同的解释,这是个坏消息。
7.4 Note: ECMA-262 defines a
block
as a list of statements. A function declaration is not a statement. 注意ECMA-262将block定义为语句列表。一个函数声明不是一个语句// bad if (currentUser) { function test() { console.log('Nope.'); } } // good let test; if (currentUser) { test = () => { console.log('Yup.'); }; }
7.5 Never name a parameter
arguments
. This will take precedence over thearguments
object that is given to every function scope. 千万不要将一个参数命名为arguments
,这将会优先于函数中本来的arguments对象在整个函数作用域内// 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
(opens new window) 千万不要使用arguments
,使用扩展运算符...
来代替。Why?
...
is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like likearguments
. why?...
明确的表达了你所想要的参数,并且,rest参数是一个真数组,而不像arguments
只是一个伪数组。// bad function concatenateAll() { const args = Array.prototype.slice.call(arguments); return args.join(''); } // good function concatenateAll(...args) { return args.join(''); }
7.7 Use default parameter syntax rather than mutating function arguments. 使用默认参数语句,而不要去改变函数的参数
// really bad function handleThings(opts) { // No! We shouldn’t mutate function arguments. // Double bad: if opts is falsy it'll be set to an object which may 当传入的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 = {}) { // ... }
7.8 Avoid side effects with default parameters. 避免默认参数带来的副作用
Why? They are confusing to reason about. why? 这么很容易使人混淆
var b = 1; // bad function count(a = b++) { console.log(a); } count(); // 1 count(); // 2 count(3); // 3 count(); // 3
7.9 Always put default parameters last. 把参数默认语法放在最后
// bad function handleThings(opts = {}, name) { // ... } // good function handleThings(name, opts = {}) { // ... }
7.10 Never use the Function constructor to create a new function. eslint:
no-new-func
(opens new window) 千万不要使用函数的构造函数去创建一个新函数Why? Creating a function in this way evaluates a string similarly to
eval()
, which opens vulnerabilities. why? 用这个方式创建函数,等同于对一个字符串使用eval()
,这会导致很多问题// 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
(opens new window)space-before-blocks
(opens new window) 在函数签名之间的空格Why? Consistency is good, and you shouldn’t have to add or remove a space when adding or removing a name. why? 一致性很好,在删除或添加名称时不需要添加或删除空格。
// 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
(opens new window) 千万不要改变参数Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller. why? 改变一个当作参数传进来的对象的值,会对原始的调用造成意想不到的副作用。
// 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
(opens new window) 千万不要重命名一个参数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 中。// 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
(opens new window) 使用扩展运算符...去调用一个参数可变的函数Why? It’s cleaner, you don’t need to supply a context, and you can not easily compose
new
withapply
. why? 这样更加简洁,你不需要提供上下文,并且你也不能轻易的使用apply来new// 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
(opens new window) 具有多行签名或者调用的函数应该像本指南中的其他多行列表一样缩进:在一行上只有一个条目,并且每个条目最后加上逗号。// bad function foo(bar, baz, quux) { // ... } // good function foo( bar, baz, quux, ) { // ... } // bad console.log(foo, bar, baz); // good console.log( foo, bar, baz, );
# Arrow Functions
8.1 When you must use an anonymous function (as when passing an inline callback), use arrow function notation. eslint:
prefer-arrow-callback
(opens new window),arrow-spacing
(opens new window) 当你必须要使用一个匿名函数当传递内联函数时,使用箭头函数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? 如果你有一个相当难懂的函数,你或许可以将逻辑移到属于以它自己命名的函数表达式
// 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 (opens new window) without side effects, omit the braces and use the implicit return. Otherwise, keep the braces and use a
return
statement. eslint:arrow-parens
(opens new window),arrow-body-style
(opens new window) 如果函数内包含一个独立的语句,返回一个没有负责用的表达式,省略括号并使用隐式返回,或者保留括号并使用return语句Why? Syntactic sugar. It reads well when multiple functions are chained together. why? 语法糖,当多个函数被链接在一起这提高了可读性
// 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; });
8.3 In case the expression spans over multiple lines, wrap it in parentheses for better readability. 万一表达式有多行,将它用括号包裹起来提高可读性
Why? It shows clearly where the function starts and ends. why? 这样可以更清楚的看到函数的结尾和开始
// bad ['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call( httpMagicObjectWithAVeryLongName, httpMethod, ) ); // good ['get', 'post', 'put'].map(httpMethod => ( Object.prototype.hasOwnProperty.call( httpMagicObjectWithAVeryLongName, httpMethod, ) ));
8.4 If your function takes a single argument and doesn’t use braces, omit the parentheses. Otherwise, always include parentheses around arguments for clarity and consistency. Note: it is also acceptable to always use parentheses, in which case use the “always” option (opens new window) for eslint. eslint:
arrow-parens
(opens new window) 如果你的函数只有一个参数,可以不使用括号。否则捏可以总是使用括号包裹以保证清晰和一致性。注意:每一次都使用括号时可以接受的。你可以使用“always” option (opens new window) for eslint. eslint:arrow-parens
(opens new window)Why? Less visual clutter. why? 减少视觉上的混乱
// bad [1, 2, 3].map((x) => x * x); // good [1, 2, 3].map(x => x * x); // good [1, 2, 3].map(number => ( `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!` )); // bad [1, 2, 3].map(x => { const y = x + 1; return x * y; }); // good [1, 2, 3].map((x) => { const y = x + 1; return x * y; });
8.5 Avoid confusing arrow function syntax (
=>
) with comparison operators (<=
,>=
). eslint:no-confusing-arrow
(opens new window) 避免对箭头函数使用比较运算符,使人困惑难懂。// 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; };
8.6 Enforce the location of arrow function bodies with implicit returns. eslint:
implicit-arrow-linebreak
(opens new window) 注意箭头函数体隐式返回的位置// bad (foo) => bar; (foo) => (bar); // good (foo) => bar; (foo) => (bar); (foo) => ( bar )
# Classes & Constructors
9.1 Always use
class
. Avoid manipulatingprototype
directly. 使用class
,避免直接使用prototype
Why?
class
syntax is more concise and easier to reason about. why?class
语法更加简洁并且可读性更好// bad function Queue(contents = []) { this.queue = [...contents]; } Queue.prototype.pop = function () { const value = this.queue[0]; this.queue.splice(0, 1); return value; }; // good class Queue { constructor(contents = []) { this.queue = [...contents]; } pop() { const value = this.queue[0]; this.queue.splice(0, 1); return value; } }
9.2 Use
extends
for inheritance. 使用extends
代替inheritanceWhy? It is a built-in way to inherit prototype functionality without breaking
instanceof
. why? 它是一个内置的方法,可以在不破坏 instanceof 的情况下继承原型功能。// bad const inherits = require('inherits'); function PeekableQueue(contents) { Queue.apply(this, contents); } inherits(PeekableQueue, Queue); PeekableQueue.prototype.peek = function () { return this.queue[0]; }; // good class PeekableQueue extends Queue { peek() { return this.queue[0]; } }
9.3 Methods can return
this
to help with method chaining. 可以通过返回this
来帮助函数链式调用// bad Jedi.prototype.jump = function () { this.jumping = true; return true; }; Jedi.prototype.setHeight = function (height) { this.height = height; }; const luke = new Jedi(); luke.jump(); // => true luke.setHeight(20); // => undefined // good class Jedi { jump() { this.jumping = true; return this; } setHeight(height) { this.height = height; return this; } } const luke = new Jedi(); luke.jump() .setHeight(20);
9.4 It’s okay to write a custom
toString()
method, just make sure it works successfully and causes no side effects. 可以去写一个自定义的toString()
方法,只需要确定它能正常工作并不会产生任何副作用class Jedi { constructor(options = {}) { this.name = options.name || 'no name'; } getName() { return this.name; } toString() { return `Jedi - ${this.getName()}`; } }
9.5 Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary. eslint:
no-useless-constructor
(opens new window) 如果没有指定默认类构造函数,则ES2015提供一个默认类构造函数。因此,不需要提供空的构造函数,或者只委托给父类// bad class Jedi { constructor() {} getName() { return this.name; } } // bad class Rey extends Jedi { constructor(...args) { super(...args); } } // good class Rey extends Jedi { constructor(...args) { super(...args); this.name = 'Rey'; } }
9.6 Avoid duplicate class members. eslint:
no-dupe-class-members
(opens new window) 避免复制类的成员Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug. why? 复制类成员的声明会默认倾向于最后一个-有重复声明很可能是一个bug
// bad class Foo { bar() { return 1; } bar() { return 2; } } // good class Foo { bar() { return 1; } } // good class Foo { bar() { return 2; } }
# Modules
10.1 Always use modules (
import
/export
) over a non-standard module system. You can always transpile to your preferred module system. 你可能经常使用模块(import/export)在非标准模块系统。你可以随时转向你更倾向的模块系统Why? Modules are the future, let’s start using the future now. why? 模块是未来的趋势。
// bad const AirbnbStyleGuide = require('./AirbnbStyleGuide'); module.exports = AirbnbStyleGuide.es6; // ok import AirbnbStyleGuide from './AirbnbStyleGuide'; export default AirbnbStyleGuide.es6; // best import { es6 } from './AirbnbStyleGuide'; export default es6;
10.2 Do not use wildcard imports. 不要使用通配符进行引入
Why? This makes sure you have a single default export. why? 这必须得保证你有一个单独的导出
// bad import * as AirbnbStyleGuide from './AirbnbStyleGuide'; // good import AirbnbStyleGuide from './AirbnbStyleGuide';
10.3 And do not export directly from an import. 不要直接从一个引入直接导出
Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent. why? 尽管少些一行会更简洁,但是用一个简洁的引入和一个简洁的导出可以使得代码一致性更好
// bad // filename es6.js export { es6 as default } from './AirbnbStyleGuide'; // good // filename es6.js import { es6 } from './AirbnbStyleGuide'; export default es6;
10.4 Only import from a path in one place. eslint:
no-duplicate-imports
(opens new window) 同一个路径只引入一次Why? Having multiple lines that import from the same path can make code harder to maintain. why? 多次引入同一路径会使得代码编的难以维护
// bad import foo from 'foo'; // … some other imports … // import { named1, named2 } from 'foo'; // good import foo, { named1, named2 } from 'foo'; // good import foo, { named1, named2, } from 'foo';
10.5 Do not export mutable bindings. eslint:
import/no-mutable-exports
(opens new window) 不要导出可变的引用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? 总体来说需要避免变化,但是在导出可变引用时属于特殊情况。 只有某些特殊的情况可能需要这种技巧,但是总的来说,只有常量可以被导出。
// bad let foo = 3; export { foo }; // good const foo = 3; export { foo };
- 10.6 In modules with a single export, prefer default export over named export.
eslint:
import/prefer-default-export
(opens new window) 在一个单一模块,导出默认模块而不是命名模块Why? To encourage more files that only ever export one thing, which is better for readability and maintainability. why? 为了鼓励更多的文件只导出一件东西,这样可读性和可维护性更好。
// bad export function foo() {} // good export default function foo() {}
10.7 Put all
import
s above non-import statements. eslint:import/first
(opens new window) 把所有导入语句放在非导入语句之上Why? Since
import
s are hoisted, keeping them all at the top prevents surprising behavior. why? 自从import
会被提升,保持它们都在最上面以防意外的情况出现。// bad import foo from 'foo'; foo.init(); import bar from 'bar'; // good import foo from 'foo'; import bar from 'bar'; foo.init();
10.8 Multiline imports should be indented just like multiline array and object literals. 多行的导入必须像多行数组和对象一样缩进,换行。
Why? The curly braces follow the same indentation rules as every other curly brace block in the style guide, as do the trailing commas. why?大括号遵循与样式指南中其他大括号相同的缩进规则,以及逗号结尾。
// bad import {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path'; // good import { longNameA, longNameB, longNameC, longNameD, longNameE, } from 'path';
10.9 Disallow Webpack loader syntax in module import statements. eslint:
import/no-webpack-loader-syntax
(opens new window) 禁止在模块导入语句中使用webpack loader语法Why? Since using Webpack syntax in the imports couples the code to a module bundler. Prefer using the loader syntax in
webpack.config.js
. 更建议在webpack.config.js
中使用loader语法// 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';
# Iterators and Generators
11.1 Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like
for-in
orfor-of
. eslint:no-iterator
(opens new window)no-restricted-syntax
(opens new window) 不要使用 iterators,推荐使用js更高阶的函数来代替比如像for-in
orfor-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, andObject.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()
去创造一个可以用来遍历对象的数组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
(opens new window) 如果你必须要使用生成器,或者你选择无视我们的建议,确保用合适的声明方式来命名函数Why?
function
and*
are part of the same conceptual keyword -*
is not a modifier forfunction
,function*
is a unique construct, different fromfunction
. why? function和*都是关键词,不是function的修饰词,function是一个与function不同的独特结构// bad function * foo() { // ... } // bad const bar = function * () { // ... }; // bad const baz = function *() { // ... }; // bad const quux = function*() { // ... }; // bad function*foo() { // ... } // bad function *foo() { // ... } // very bad function * foo() { // ... } // very bad const wat = function * () { // ... }; // good function* foo() { // ... } // good const foo = function* () { // ... };
# Properties
12.1 Use dot notation when accessing properties. eslint:
dot-notation
(opens new window) 使用点号去访问一个属性const luke = { jedi: true, age: 28, }; // bad const isJedi = luke['jedi']; // good const isJedi = luke.jedi;
12.2 Use bracket notation
[]
when accessing properties with a variable. 当使用一个变量去接受一个属性之的时候用[]const luke = { jedi: true, age: 28, }; function getProp(prop) { return luke[prop]; } const isJedi = getProp('jedi');
12.3 Use exponentiation operator
**
when calculating exponentiations. eslint:no-restricted-properties
(opens new window). 使用求幂运算符 ** 当你要计算求幂时// bad const binary = Math.pow(2, 10); // good const binary = 2 ** 10;
# Variables
13.1 Always use
const
orlet
to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that. eslint:no-undef
(opens new window)prefer-const
(opens new window) 建议使用const和let来定义变量。不这样做会导致全局变量,我们想要尽可能避免污染全局命名空间。行星船长也这么警告过我们。// bad superPower = new SuperPower(); // good const superPower = new SuperPower();
13.2 Use one
const
orlet
declaration per variable or assignment. eslint:one-var
(opens new window) 对每一个变量或者赋值使用一个const或者letWhy? 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对每一个变量进行步进,而不是一次跳过所有的声明。// 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
const
s and then group all yourlet
s. 先将所有的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? 当以后您可能需要根据前面分配的变量分配变量时,这是很有帮助的。
// 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
andconst
are block scoped and not function scoped. why?let
和const
是块级作用域而不是函数作用域// 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
(opens new window) 不要链式的定义变量Why? Chaining variable assignments creates implicit global variables. why? 链式定义变量会隐式的生产全局变量
// 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 (
++
,--
). eslintno-plusplus
(opens new window) 避免使用一元加号和自增自减Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like
num += 1
instead ofnum++
ornum ++
. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs. why? 根据eslint文档,一元加号和减号语句受自动分号插入的影响,会在应用中造成无声错误。使用类似num += 1
来代替num++
ornum ++
也可以更好的表达含义。不允许使用一元加号,减号同样可以防止你无意中改变了你的变量值,这可能会造成预期之外的表现。// 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 violatesmax-len
(opens new window), surround the value in parens. eslintoperator-linebreak
(opens new window).、 避免在赋值语句中=
前后换行。实在长度超出了,请用括号将其包裹起来Why? Linebreaks surrounding
=
can obfuscate the value of an assignment.// 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
(opens new window) 不允许未被使用的变量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? 代码中有定义了而未被使用变量很可能是由于不完整的重构而导致的错误。这些变量不仅占用空间,还会对读者造成困惑。
// 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.
# Hoisting(提升)
14.1
var
declarations get hoisted to the top of their closest enclosing function scope, their assignment does not.const
andlet
declarations are blessed with a new concept called Temporal Dead Zones (TDZ) (opens new window). It’s important to know why typeof is no longer safe (opens new window). 用var
的声明会提升到最近闭合的函数作用于的顶部,但是它们的赋值并不会。const和let声明被赋予了一个新的概念叫暂时死亡区域?了解为什么typeof不再安全是很重要的。// we know this wouldn’t work (assuming there // is no notDefined global variable) function example() { console.log(notDefined); // => throws a ReferenceError } // creating a variable declaration after you // reference the variable will work due to // variable hoisting. Note: the assignment // value of `true` is not hoisted. function example() { console.log(declaredButNotAssigned); // => undefined var declaredButNotAssigned = true; } // the interpreter is hoisting the variable // declaration to the top of the scope, // which means our example could be rewritten as: function example() { let declaredButNotAssigned; console.log(declaredButNotAssigned); // => undefined declaredButNotAssigned = true; } // using const and let function example() { console.log(declaredButNotAssigned); // => throws a ReferenceError console.log(typeof declaredButNotAssigned); // => throws a ReferenceError const declaredButNotAssigned = true; }
14.2 Anonymous function expressions hoist their variable name, but not the function assignment. 匿名函数的变量名会提升,但是函数体的赋值并不会
function example() { console.log(anonymous); // => undefined anonymous(); // => TypeError anonymous is not a function var anonymous = function () { console.log('anonymous function expression'); }; }
14.3 Named function expressions hoist the variable name, not the function name or the function body. 具名函数表达式提升变量名,而不是函数名或函数体。
function example() { console.log(named); // => undefined named(); // => TypeError named is not a function superPower(); // => ReferenceError superPower is not defined var named = function superPower() { console.log('Flying'); }; } // the same is true when the function name // is the same as the variable name. function example() { console.log(named); // => undefined named(); // => TypeError named is not a function var named = function named() { console.log('named'); }; }
14.4 Function declarations hoist their name and the function body. 函数声明不过会提升他们的名字还会提升函数体。
function example() { superPower(); // => Flying function superPower() { console.log('Flying'); } }
For more information refer to JavaScript Scoping & Hoisting (opens new window) by Ben Cherry (opens new window).
# Comparison Operators & Equality (比较运算符和等号)
- 15.1 Use
===
and!==
over==
and!=
. eslint:eqeqeq
(opens new window) 使用===和!==而不是 == 和 !=
15.2 Conditional statements such as the
if
statement evaluate their expression using coercion with theToBoolean
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
if ([0] && []) { // true // an array (even an empty one) is an object, objects will evaluate to true }
15.3 Use shortcuts for booleans, but explicit comparisons for strings and numbers. 可以使用简写来求布尔值,但比较字符串和数字要明确的写清楚。
// bad if (isValid === true) { // ... } // good if (isValid) { // ... } // bad if (name) { // ... } // good if (name !== '') { // ... } // bad if (collection.length) { // ... } // good if (collection.length > 0) { // ... }
- 15.4 For more information see Truth Equality and JavaScript (opens new window) by Angus Croll.
15.5 Use braces to create blocks in
case
anddefault
clauses that contain lexical declarations (e.g.let
,const
,function
, andclass
). eslint:no-case-declarations
(opens new window) 在 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 itscase
is reached. This causes problems when multiplecase
clauses attempt to define the same thing. why? 因为在整个switch快中,变量的声明都是可见的,虽然并未复制,以防影响到其他的case情况,使用大括号来创建快级作用域消除对其他case情况的影响。// 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
(opens new window) 三元表达式通常都是单行的,不应该被嵌套// 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;
15.7 Avoid unneeded ternary statements. eslint:
no-unneeded-ternary
(opens new window) 避免没有必要的三元表达式// 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;
15.8 When mixing operators, enclose them in parentheses. The only exception is the standard arithmetic operators (
+
,-
,*
, &/
) since their precedence is broadly understood. eslint:no-mixed-operators
(opens new window) 当混合运算符时,将他们用圆括号包裹起来。除了标准运算符(+
,-
,*
, &/
) ,因为他们的优先级被广泛理解。Why? This improves readability and clarifies the developer’s intention. why? 这提高了代码的可读性并清楚的表达了
// 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;
# Blocks 块
16.1 Use braces with all multi-line blocks. eslint:
nonblock-statement-body-position
(opens new window) 使用括号讲多行的块包裹起来// bad if (test) return false; // good if (test) return false; // good if (test) { return false; } // bad function foo() { return false; } // good function bar() { return false; }
16.2 If you’re using multi-line blocks with
if
andelse
, putelse
on the same line as yourif
block’s closing brace. eslint:brace-style
(opens new window) 如果你在if和else语句中使用了多行代码块,请将eles同样放在if闭合的括号旁边。// bad if (test) { thing1(); thing2(); } else { thing3(); } // good if (test) { thing1(); thing2(); } else { thing3(); }
16.3 If an
if
block always executes areturn
statement, the subsequentelse
block is unnecessary. Areturn
in anelse if
block following anif
block that contains areturn
can be separated into multipleif
blocks. eslint:no-else-return
(opens new window) 如果一个if代码块总是有分开的return语句,随后的eles语句并不是必须的。如果一个包含 return 语句的 else if 块,在一个包含了 return 语句的 if 块之后,那么可以拆成多个 if 块。// 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; } }
# Control Statements (控制语句)
17.1 In case your control statement (
if
,while
etc.) gets too long or exceeds the maximum line length, each (grouped) condition could be put into a new line. The logical operator should begin the line. 如果你的控制语句(if while等)太长或者超出最大的行宽,每一个条件语句可以分成新的一行,逻辑运算符必须放在行首。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? 在行头要求操作符保持对齐,并遵循类似的方法链模式,这样也提高了代码的可读性,并使其更容易的展示了复杂的逻辑。
// 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(); }
17.2 Don't use selection operators in place of control statements. 不要用选择运算符来代替控制语句
// bad !isRunning && startRunning(); // good if (!isRunning) { startRunning(); }
# Comments
18.1 Use
/** ... */
for multi-line comments. 使用/** ... */
进行多行注释// bad // make() returns a new element // based on the passed in tag name // // @param {String} tag // @return {Element} element function make(tag) { // ... return element; } // good /** * make() returns a new element * based on the passed-in tag name */ function make(tag) { // ... return element; }
18.2 Use
//
for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it’s on the first line of a block. 使用//
进行单行注释。请注释主题的上方放置新的一行注释。除非注释在块的第一行,不然前面空一行。// 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; }
18.3 Start all comments with a space to make it easier to read. eslint:
spaced-comment
(opens new window) 在所有注释的前一行都空格,使其可读性更强。// 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; }
- 18.4 Prefixing your comments with
FIXME
orTODO
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 areFIXME: -- need to figure this out
orTODO: -- need to implement
. 在注释前添加FIXME
或者TODO
去帮助开发人员更好地里面你是否需要重写这个问题,或者如果你建议需要实现一个解决该问题的方式。这些注释与常规的注释不同,因为他们是可操作的。
18.5 Use
// FIXME:
to annotate problems. 使用// FIXME
去注释一个问题class Calculator extends Abacus { constructor() { super(); // FIXME: shouldn’t use a global here total = 0; } }
18.6 Use
// TODO:
to annotate solutions to problems. 使用// TODO
来注释一个问题的解决方法class Calculator extends Abacus { constructor() { super(); // TODO: total should be configurable by an options param this.total = 0; } }
# Whitespace
19.1 Use soft tabs (space character) set to 2 spaces. eslint:
indent
(opens new window) 使用tab缩进设置成两个空格// bad function foo() { ∙∙∙∙let name; } // bad function bar() { ∙let name; } // good function baz() { ∙∙let name; }
19.2 Place 1 space before the leading brace. eslint:
space-before-blocks
(opens new window) 在主体前放一个空格// 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', });
19.3 Place 1 space before the opening parenthesis in control statements (
if
,while
etc.). Place no space between the argument list and the function name in function calls and declarations. eslint:keyword-spacing
(opens new window) 在控制语句的括号前面放一个空格。在函数调用和声明之间,和参数列表和函数名之前不放空格。// bad if(isJedi) { fight (); } // good if (isJedi) { fight(); } // bad function fight () { console.log ('Swooosh!'); } // good function fight() { console.log('Swooosh!'); }
19.4 Set off operators with spaces. eslint:
space-infix-ops
(opens new window) 用空格将运算符分开// bad const x=y+5; // good const x = y + 5;
19.5 End files with a single newline character. eslint:
eol-last
(opens new window) 在文件的结尾用新一个单独的回车换行符。// bad import { es6 } from './AirbnbStyleGuide'; // ... export default es6;
// bad import { es6 } from './AirbnbStyleGuide'; // ... export default es6;↵ ↵
// good import { es6 } from './AirbnbStyleGuide'; // ... export default es6;↵
19.6 Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which emphasizes that the line is a method call, not a new statement. eslint:
newline-per-chained-call
(opens new window)no-whitespace-before-property
(opens new window) 当书写长的链式函数(超过两个方法)时。在行首使用点号,这样可以强调这是一个函数方法调用而不是一个声明。// 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);
19.7 Leave a blank line after blocks and before the next statement. 在每一个快之后和下一个声明之前空行
// 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;
19.8 Do not pad your blocks with blank lines. eslint:
padded-blocks
(opens new window) 不要用空行填充块。// 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); }
19.9 Do not add spaces inside parentheses. eslint:
space-in-parens
(opens new window) 不要在括号内添加空格// bad function bar( foo ) { return foo; } // good function bar(foo) { return foo; } // bad if ( foo ) { console.log(foo); } // good if (foo) { console.log(foo); }
19.10 Do not add spaces inside brackets. eslint:
array-bracket-spacing
(opens new window) 不要在大括号内侧添加空格// bad const foo = [ 1, 2, 3 ]; console.log(foo[ 0 ]); // good const foo = [1, 2, 3]; console.log(foo[0]);
19.11 Add spaces inside curly braces. eslint:
object-curly-spacing
(opens new window) 在花括号的两侧添加空格// bad const foo = {clark: 'kent'}; // good const foo = { clark: 'kent' };
19.12 Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per above, long strings are exempt from this rule, and should not be broken up. eslint:
max-len
(opens new window) 避免一行代码超过100个字符(包括空格)。注意:根据以上规则,长字符串不受此规则约束,并且不应该被打断Why? This ensures readability and maintainability. why? 这样保证了可读性和可维护性
// 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.'));
19.13 Require consistent spacing inside an open block token and the next token on the same line. This rule also enforces consistent spacing inside a close block token and previous token on the same line. eslint:
block-spacing
(opens new window) 代码块空格请保持一致// bad function foo() {return true;} if (foo) { bar = 0;} // good function foo() { return true; } if (foo) { bar = 0; }
19.14 Avoid spaces before commas and require a space after commas. eslint:
comma-spacing
(opens new window) 不要在逗号前空格,在逗号后空格// bad var foo = 1,bar = 2; var arr = [1 , 2]; // good var foo = 1, bar = 2; var arr = [1, 2];
19.15 Enforce spacing inside of computed properties. eslint:
computed-property-spacing
(opens new window) 强制计算属性内使用空格// bad obj[foo ] obj[ 'foo'] var x = {[ b ]: a} obj[foo[ bar ]] // good obj[foo] obj['foo'] var x = { [b]: a } obj[foo[bar]]
19.16 Avoid spaces between functions and their invocations. eslint:
func-call-spacing
(opens new window) 避免函数调用直接的空格// bad func (); func (); // good func();
19.17 Enforce spacing between keys and values in object literal properties. eslint:
key-spacing
(opens new window) 在对象文字属性中要求键和值之间的间隔。// bad var obj = { "foo" : 42 }; var obj2 = { "foo":42 }; // good var obj = { "foo": 42 };
- 19.18 Avoid trailing spaces at the end of lines. eslint:
no-trailing-spaces
(opens new window) 避免行尾跟着空格
19.19 Avoid multiple empty lines and only allow one newline at the end of files. eslint:
no-multiple-empty-lines
(opens new window) 避免多个空行,并且只允许在文件末尾有一个换行符// bad var x = 1; var y = 2; // good var x = 1; var y = 2;
# Commas
20.1 Leading commas: Nope. eslint:
comma-style
(opens new window) 不要把逗号写在行首// 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', };
20.2 Additional trailing comma: Yup. eslint:
comma-dangle
(opens new window) 在尾部添加一个额外的逗号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 (opens new window) in legacy browsers. why?这可以是git diff更加的清晰。此外,像babel这样的预处理器会讲多余的逗号去除掉,所以不用担心老版本浏览器的解析问题
// 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'], };
// 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 );
# Semicolons
21.1 Yup. eslint:
semi
(opens new window)Why? When JavaScript encounters a line break without a semicolon, it uses a set of rules called Automatic Semicolon Insertion (opens new window) 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 以捕获缺少的分号将有助于防止你遇到的问题。
// 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'; }
# Type Casting & Coercion (类型转换和强制类型转换)
- 22.1 Perform type coercion at the beginning of the statement. 在语句的开始部分进行类型转换
22.2 Strings: eslint:
no-new-wrappers
(opens new window)// => 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);
22.3 Numbers: Use
Number
for type casting andparseInt
always with a radix for parsing strings. eslint:radix
(opens new window)no-new-wrappers
(opens new window) 使用Number进行类型转换,转化字符串的时候用带基数的parseIntconst 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);
22.4 If for whatever reason you are doing something wild and
parseInt
is your bottleneck and need to use Bitshift for performance reasons (opens new window), leave a comment explaining why and what you’re doing. 如果你一定要使用这种bitshift,请留下注释,你为什么要这么做。// 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;
22.5 Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values (opens new window), but bitshift operations always return a 32-bit integer (source (opens new window)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion (opens new window). Largest signed 32-bit Int is 2,147,483,647: 注意:当你使用位运算的时候要小心。 数字总是被以 64-bit 值 的形式表示,但是位运算总是返回一个 32-bit 的整数 (来源)。 对于大于 32 位的整数值,位运算可能会导致意外行为。讨论。 最大的 32 位整数是: 2,147,483,647。
2147483647 >> 0; // => 2147483647 2147483648 >> 0; // => -2147483648 2147483649 >> 0; // => -2147483647
22.6 Booleans: eslint:
no-new-wrappers
(opens new window)const age = 0; // bad const hasAge = new Boolean(age); // good const hasAge = Boolean(age); // best const hasAge = !!age;
# Naming Conventions(命名规则)
23.1 Avoid single letter names. Be descriptive with your naming. eslint:
id-length
(opens new window) 避免单个字符的命名// bad function q() { // ... } // good function query() { // ... }
23.2 Use camelCase when naming objects, functions, and instances. eslint:
camelcase
(opens new window) 使用驼峰命名对象,函数和实例。// bad const OBJEcttsssss = {}; const this_is_my_object = {}; function c() {} // good const thisIsMyObject = {}; function thisIsMyFunction() {}
23.3 Use PascalCase only when naming constructors or classes. eslint:
new-cap
(opens new window) 当命名构造器和类的时候,使用PascalCase// 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', });
23.4 Do not use trailing or leading underscores. eslint:
no-underscore-dangle
(opens new window) 不要在命名前后使用下划线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.
// 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');
23.5 Don’t save references to
this
. Use arrow functions or Function#bind (opens new window). 不要保存this
的引用// 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); }; }
23.6 A base filename should exactly match the name of its default export. 一个基本的文件名需要与其默认导出的名称完全匹配。
// 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
23.7 Use camelCase when you export-default a function. Your filename should be identical to your function’s name. 当你导出一个默认函数时使用驼峰的方式。你的文件名应该和你的函数名一致。
function makeStyleGuide() { // ... } export default makeStyleGuide;
23.8 Use PascalCase when you export a constructor / class / singleton / function library / bare object. 何时使用帕斯卡命名,当你导出构造器,类,单例,函数库,空对象时。
const AirbnbStyleGuide = { es6: { }, }; export default AirbnbStyleGuide;
23.9 Acronyms and initialisms should always be all capitalized, or all lowercased. 首字母缩写的词应该都为大写或者都为小写
Why? Names are for readability, not to appease a computer algorithm. why? 名字是为了可读性,不是为了满足计算机的算法。
// 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. - 导出的对象是否需要?在导出的顶层使用,并保持所有的嵌套属性不变的情况下。
// 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' };
- What about all
# 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()
andsetVal('hello')
. 不要使用 JavaScript 的 getters/setters 方法,因为它们会导致意外的副作用,并且更加难以测试、维护和推敲。 相应的,如果你需要存取函数的时候使用 getVal() 和 setVal('hello')。// bad class Dragon { get age() { // ... } set age(value) { // ... } } // good class Dragon { getAge() { // ... } setAge(value) { // ... } }
24.3 If the property/method is a
boolean
, useisVal()
orhasVal()
. 如果属性名或方法返回的是布尔值,使用isVal()
orhasVal()
.// bad if (!dragon.age()) { return false; } // good if (!dragon.hasAge()) { return false; }
24.4 It’s okay to create
get()
andset()
functions, but be consistent. 如果要创建get()和set()函数,请保持一致性class Jedi { constructor(options = {}) { const lightsaber = options.lightsaber || 'blue'; this.set('lightsaber', lightsaber); } set(key, val) { this[key] = val; } get(key) { return this[key]; } }
# Events (事件)
25.1 When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass an object literal (also known as a "hash") instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of: 当给事件附加数据时(无论是DOM事件还是更加私有的事件,传递一个对象而不是原始值。这样可以让后续的开发者更有效给这个事件添加数据,而不需要找到并更新这个事件的所有事件。
// bad $(this).trigger('listingUpdated', listing.id); // ... $(this).on('listingUpdated', (e, listingID) => { // do something with listingID });
prefer:
// good $(this).trigger('listingUpdated', { listingID: listing.id }); // ... $(this).on('listingUpdated', (e, data) => { // do something with data.listingID });
# jQuery
26.1 Prefix jQuery object variables with a
$
. 在JQuery对象的声明加上$
的前缀// bad const sidebar = $('.sidebar'); // good const $sidebar = $('.sidebar'); // good const $sidebarBtn = $('.sidebar-btn');
26.2 Cache jQuery lookups. 缓存JQuery的查询对象。
// bad function setSidebar() { $('.sidebar').hide(); // ... $('.sidebar').css({ 'background-color': 'pink', }); } // good function setSidebar() { const $sidebar = $('.sidebar'); $sidebar.hide(); // ... $sidebar.css({ 'background-color': 'pink', }); }
- 26.3 For DOM queries use Cascading
$('.sidebar ul')
or parent > child$('.sidebar > ul')
. jsPerf (opens new window) 在DOM查询中使用串联的查询方式$('.sidebar ul')
或者父 > 子$('.sidebar > ul')
26.4 Use
find
with scoped jQuery object queries. 基于JQuery的对象作用域使用find方法// bad $('ul', '.sidebar').hide(); // bad $('.sidebar').find('ul').hide(); // good $('.sidebar ul').hide(); // good $('.sidebar > ul').hide(); // good $sidebar.find('ul').hide();
# ECMAScript 5 Compatibility
- 27.1 Refer to Kangax (opens new window)’s ES5 compatibility table (opens new window).
- ECMAScript5的兼容性参考以上链接
# ECMAScript 6+ (ES 2015+) Styles
- 28.1 This is a collection of links to the various ES6+ features.
- 这是一个链接ES6+特性的合集
- Arrow Functions箭头函数
- Classes类
- Object Shorthand对象简写
- Object Concise对象简洁
- Object Computed Properties对象计算属性
- Template Strings模版字符串
- Destructuring解构
- Default Parameters默认参数
- Restrest运算符
- Array Spreads数组扩展
- Let and Constlet和const
- Exponentiation Operator取幂运算符
- Iterators and Generators迭代器和生成器
- Modules模块
28.2 Do not use TC39 proposals (opens new window) that have not reached stage 3. 不要使用尚未达到第3阶段的 TC39 建议。
Why? They are not finalized (opens new window), and they are subject to change or to be withdrawn entirely. We want to use JavaScript, and proposals are not JavaScript yet.
# Standard Library (标准库)
The Standard Library (opens new window) contains utilities that are functionally broken but remain for legacy reasons. 标准库包含的一些实用方法在功能上有缺陷,但是由于历史遗留原因仍然存在。
29.1 Use
Number.isNaN
instead of globalisNaN
. eslint:no-restricted-globals
(opens new window) 使用Number.isNan来代替全局的isNaNWhy? 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. 如果你需要这种行为,请注明// 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 globalisFinite
. eslint:no-restricted-globals
(opens new window)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. 如使用请注明。// bad isFinite('2e3'); // true // good Number.isFinite('2e3'); // false Number.isFinite(parseInt('2e3', 10)); // true
# Testing (测试)
30.1 Yup.
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
(opens new window) andjest
(opens new window) at Airbnb.tape
(opens new window) 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在将来几乎肯定会再次崩溃。
# Performance (性能)
- On Layout & Web Performance (opens new window)
- String vs Array Concat (opens new window)
- Try/Catch Cost In a Loop (opens new window)
- Bang Function (opens new window)
- jQuery Find vs Context, Selector (opens new window)
- innerHTML vs textContent for script text (opens new window)
- Long String Concatenation (opens new window)
- Are Javascript functions like
map()
,reduce()
, andfilter()
optimized for traversing arrays? (opens new window) - Loading...
# Resources (资源)
Learning ES6+
- Latest ECMA spec (opens new window)
- ExploringJS (opens new window)
- ES6 Compatibility Table (opens new window)
- Comprehensive Overview of ES6 Features (opens new window)
Read This
Tools
- Code Style Linters
- Neutrino Preset - @neutrinojs/airbnb (opens new window)
Other Style Guides
- Google JavaScript Style Guide (opens new window)
- jQuery Core Style Guidelines (opens new window)
- Principles of Writing Consistent, Idiomatic JavaScript (opens new window)
- StandardJS (opens new window)
Other Styles
- Naming this in nested functions (opens new window) - Christian Johansen
- Conditional Callbacks (opens new window) - Ross Allen
- Popular JavaScript Coding Conventions on GitHub (opens new window) - JeongHoon Byun
- Multiple var statements in JavaScript, not superfluous (opens new window) - Ben Alman
Further Reading
- Understanding JavaScript Closures (opens new window) - Angus Croll
- Basic JavaScript for the impatient programmer (opens new window) - Dr. Axel Rauschmayer
- You Might Not Need jQuery (opens new window) - Zack Bloom & Adam Schwartz
- ES6 Features (opens new window) - Luke Hoban
- Frontend Guidelines (opens new window) - Benjamin De Cock
Books
- JavaScript: The Good Parts (opens new window) - Douglas Crockford
- JavaScript Patterns (opens new window) - Stoyan Stefanov
- Pro JavaScript Design Patterns (opens new window) - Ross Harmes and Dustin Diaz
- High Performance Web Sites: Essential Knowledge for Front-End Engineers (opens new window) - Steve Souders
- Maintainable JavaScript (opens new window) - Nicholas C. Zakas
- JavaScript Web Applications (opens new window) - Alex MacCaw
- Pro JavaScript Techniques (opens new window) - John Resig
- Smashing Node.js: JavaScript Everywhere (opens new window) - Guillermo Rauch
- Secrets of the JavaScript Ninja (opens new window) - John Resig and Bear Bibeault
- Human JavaScript (opens new window) - Henrik Joreteg
- Superhero.js (opens new window) - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy
- JSBooks (opens new window) - Julien Bouquillon
- Third Party JavaScript (opens new window) - Ben Vinegar and Anton Kovalyov
- Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript (opens new window) - David Herman
- Eloquent JavaScript (opens new window) - Marijn Haverbeke
- You Don’t Know JS: ES6 & Beyond (opens new window) - Kyle Simpson
Blogs
- JavaScript Weekly (opens new window)
- JavaScript, JavaScript... (opens new window)
- Bocoup Weblog (opens new window)
- Adequately Good (opens new window)
- NCZOnline (opens new window)
- Perfection Kills (opens new window)
- Ben Alman (opens new window)
- Dmitry Baranovskiy (opens new window)
- nettuts (opens new window)
Podcasts
# In the Wild
This is a list of organizations that are using this style guide. Send us a pull request and we'll add you to the list.
- 123erfasst: 123erfasst/javascript (opens new window)
- 3blades: 3Blades (opens new window)
- 4Catalyzer: 4Catalyzer/javascript (opens new window)
- Aan Zee: AanZee/javascript (opens new window)
- Adult Swim: adult-swim/javascript (opens new window)
- Airbnb: airbnb/javascript (opens new window)
- AltSchool: AltSchool/javascript (opens new window)
- Apartmint: apartmint/javascript (opens new window)
- Ascribe: ascribe/javascript (opens new window)
- Avalara: avalara/javascript (opens new window)
- Avant: avantcredit/javascript (opens new window)
- Axept: axept/javascript (opens new window)
- BashPros: BashPros/javascript (opens new window)
- Billabong: billabong/javascript (opens new window)
- Bisk: bisk (opens new window)
- Bonhomme: bonhommeparis/javascript (opens new window)
- Brainshark: brainshark/javascript (opens new window)
- CaseNine: CaseNine/javascript (opens new window)
- Cerner: Cerner (opens new window)
- Chartboost: ChartBoost/javascript-style-guide (opens new window)
- ComparaOnline: comparaonline/javascript (opens new window)
- Compass Learning: compasslearning/javascript-style-guide (opens new window)
- DailyMotion: dailymotion/javascript (opens new window)
- DoSomething: DoSomething/eslint-config (opens new window)
- Digitpaint digitpaint/javascript (opens new window)
- Drupal: www.drupal.org (opens new window)
- Ecosia: ecosia/javascript (opens new window)
- Evernote: evernote/javascript-style-guide (opens new window)
- Evolution Gaming: evolution-gaming/javascript (opens new window)
- EvozonJs: evozonjs/javascript (opens new window)
- ExactTarget: ExactTarget/javascript (opens new window)
- Expensify Expensify/Style-Guide (opens new window)
- Flexberry: Flexberry/javascript-style-guide (opens new window)
- Gawker Media: gawkermedia (opens new window)
- General Electric: GeneralElectric/javascript (opens new window)
- Generation Tux: GenerationTux/javascript (opens new window)
- GoodData: gooddata/gdc-js-style (opens new window)
- GreenChef: greenchef/javascript (opens new window)
- Grooveshark: grooveshark/javascript (opens new window)
- Grupo-Abraxas: Grupo-Abraxas/javascript (opens new window)
- Honey: honeyscience/javascript (opens new window)
- How About We: howaboutwe/javascript (opens new window)
- Huballin: huballin (opens new window)
- HubSpot: HubSpot/javascript (opens new window)
- Hyper: hyperoslo/javascript-playbook (opens new window)
- InterCity Group: intercitygroup/javascript-style-guide (opens new window)
- Jam3: Jam3/Javascript-Code-Conventions (opens new window)
- JeopardyBot: kesne/jeopardy-bot (opens new window)
- JSSolutions: JSSolutions/javascript (opens new window)
- Kaplan Komputing: kaplankomputing/javascript (opens new window)
- KickorStick: kickorstick (opens new window)
- Kinetica Solutions: kinetica/javascript (opens new window)
- LEINWAND: LEINWAND/javascript (opens new window)
- Lonely Planet: lonelyplanet/javascript (opens new window)
- M2GEN: M2GEN/javascript (opens new window)
- Mighty Spring: mightyspring/javascript (opens new window)
- MinnPost: MinnPost/javascript (opens new window)
- MitocGroup: MitocGroup/javascript (opens new window)
- ModCloth: modcloth/javascript (opens new window)
- Money Advice Service: moneyadviceservice/javascript (opens new window)
- Muber: muber (opens new window)
- National Geographic: natgeo (opens new window)
- Nimbl3: nimbl3/javascript (opens new window)
- Nulogy: nulogy/javascript (opens new window)
- Orange Hill Development: orangehill/javascript (opens new window)
- Orion Health: orionhealth/javascript (opens new window)
- OutBoxSoft: OutBoxSoft/javascript (opens new window)
- Peerby: Peerby/javascript (opens new window)
- Pier 1: Pier1/javascript (opens new window)
- Qotto: Qotto/javascript-style-guide (opens new window)
- Razorfish: razorfish/javascript-style-guide (opens new window)
- reddit: reddit/styleguide/javascript (opens new window)
- React: facebook.github.io/react/contributing/how-to-contribute.html#style-guide (opens new window)
- REI: reidev/js-style-guide (opens new window)
- Ripple: ripple/javascript-style-guide (opens new window)
- Sainsbury’s Supermarkets: jsainsburyplc (opens new window)
- SeekingAlpha: seekingalpha/javascript-style-guide (opens new window)
- Shutterfly: shutterfly/javascript (opens new window)
- Sourcetoad: sourcetoad/javascript (opens new window)
- Springload: springload (opens new window)
- StratoDem Analytics: stratodem/javascript (opens new window)
- SteelKiwi Development: steelkiwi/javascript (opens new window)
- StudentSphere: studentsphere/javascript (opens new window)
- SwoopApp: swoopapp/javascript (opens new window)
- SysGarage: sysgarage/javascript-style-guide (opens new window)
- Syzygy Warsaw: syzygypl/javascript (opens new window)
- Target: target/javascript (opens new window)
- TheLadders: TheLadders/javascript (opens new window)
- The Nerdery: thenerdery/javascript-standards (opens new window)
- T4R Technology: T4R-Technology/javascript (opens new window)
- UrbanSim: urbansim (opens new window)
- VoxFeed: VoxFeed/javascript-style-guide (opens new window)
- WeBox Studio: weboxstudio/javascript (opens new window)
- Weggo: Weggo/javascript (opens new window)
- Zillow: zillow/javascript (opens new window)
- ZocDoc: ZocDoc/javascript (opens new window)
# Translation
This style guide is also available in other languages:
Brazilian Portuguese: armoucar/javascript-style-guide (opens new window)
Bulgarian: borislavvv/javascript (opens new window)
Catalan: fpmweb/javascript-style-guide (opens new window)
Chinese (Simplified): lin-123/javascript (opens new window)
Chinese (Traditional): jigsawye/javascript (opens new window)
French: nmussy/javascript-style-guide (opens new window)
German: timofurrer/javascript-style-guide (opens new window)
Italian: sinkswim/javascript-style-guide (opens new window)
Japanese: mitsuruog/javascript-style-guide (opens new window)
Korean: ParkSB/javascript-style-guide (opens new window)
Russian: leonidlebedev/javascript-airbnb (opens new window)
Spanish: paolocarrasco/javascript-style-guide (opens new window)
Thai: lvarayut/javascript-style-guide (opens new window)
Turkish: eraycetinay/javascript (opens new window)
Ukrainian: ivanzusko/javascript (opens new window)
Vietnam: hngiang/javascript-style-guide (opens new window)
# The JavaScript Style Guide Guide
# Chat With Us About JavaScript
- Find us on gitter (opens new window).
# 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.
# 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.