使用 JavaScript 最合理的方式。
注意: 这个指南假定你正在使用 Babel,并且需要你使用 babel-preset-airbnb 或与其等效的预设。同时假定你在你的应用里安装了 带有 airbnb-browser-shims 或与其等效的插件的
shims/polyfills。

这个指南支持的其他语言翻译版请看 Translation。
其他风格指南:
1.1 基本类型: 你可以直接获取到基本类型的值
stringnumberbooleannullundefinedsymbolbigint
constfoo=1;letbar=foo;bar=9;console.log(foo,bar);// => 1, 9
- 由于 Symbols 和 BigInts 不能被正确的 polyfill。所以不应在不能原生支持这些类型的环境或浏览器中使用他们。
1.2 复杂类型: 复杂类型赋值是获取到他的引用的值。
objectarrayfunction
constfoo=[1,2];constbar=foo;bar[0]=9;console.log(foo[0],bar[0]);// => 9, 9
2.1 所有的赋值都用
const,避免使用var。eslint:prefer-const,no-const-assign为什么?因为这个能确保你不会改变你的初始值,重复引用会导致 bug 并且使代码变得难以理解。
// badvara=1;varb=2;// goodconsta=1;constb=2;
2.2 如果你一定要对参数重新赋值,使用
let,而不是var。eslint:no-var为什么?因为
let是块级作用域,而var是函数级作用域。// badvarcount=1;if(true){count+=1;}// good, use the let.letcount=1;if(true){count+=1;}
2.3 注意:
let和const都是块级作用域, 而var是函数级作用域// const 和 let 都只存在于它被定义的那个块级作用域。{leta=1;constb=1;varc=1;}console.log(a);// 引用错误console.log(b);// 引用错误console.log(c);// 打印 1
上面的代码里,
a和b的定义会报引用错误,这是因为a和b是块级作用域, 而c的作用域是在函数里的。
3.1 使用字面值创建对象。eslint:
no-new-object// badconstitem=newObject();// goodconstitem={};
3.2 使用计算属性名创建一个带有动态属性名的对象。
为什么?因为这可以使你在同一个地方定义所有对象属性。
functiongetKey(k){return`a key named ${k}`;}// badconstobj={id: 5,name: 'San Francisco',};obj[getKey('enabled')]=true;// goodconstobj={id: 5,name: 'San Francisco',[getKey('enabled')]: true,};
3.3 用对象方法简写。eslint:
object-shorthand// badconstatom={value: 1,addValue: function(value){returnatom.value+value;},};// goodconstatom={value: 1,// 对象的方法addValue(value){returnatom.value+value;},};
3.4 用属性值缩写。eslint:
object-shorthand为什么?这样写更简洁,且可读性更高。
constlukeSkywalker='Luke Skywalker';// badconstobj={lukeSkywalker: lukeSkywalker,};// goodconstobj={ lukeSkywalker,};
3.5 将你的所有缩写放在对象声明的前面。
为什么?因为这样能更方便地知道有哪些属性用了缩写。
constanakinSkywalker='Anakin Skywalker';constlukeSkywalker='Luke Skywalker';// badconstobj={episodeOne: 1,twoJediWalkIntoACantina: 2, lukeSkywalker,episodeThree: 3,mayTheFourth: 4, anakinSkywalker,};// goodconstobj={ lukeSkywalker, anakinSkywalker,episodeOne: 1,twoJediWalkIntoACantina: 2,episodeThree: 3,mayTheFourth: 4,};
3.6 只对那些无效的标示使用引号
''。eslint:quote-props为什么?通常我们认为这种方式主观上更易读。不仅优化了代码高亮,而且也更容易被许多 JS 引擎优化。
// badconstbad={'foo': 3,'bar': 4,'data-blah': 5,};// goodconstgood={foo: 3,bar: 4,'data-blah': 5,};
3.7 不要直接调用
Object.prototype上的方法,如hasOwnProperty、propertyIsEnumerable、isPrototypeOf。eslint: [no-prototype-builtins](htt ps://eslint.org/docs/rules/no-prototype-builtins)为什么?在一些有问题的对象上,这些方法可能会被屏蔽掉,如:
{ hasOwnProperty: false }或空对象Object.create(null)。 在支持 ES2022 的现代浏览器中,或者被做过类似 https://npmjs.com/object.hasown 的兼容情况下,Object.hasOwn也会被用作Object.prototype.hasOwnProperty.call的替代品。// badconsole.log(object.hasOwnProperty(key));// goodconsole.log(Object.prototype.hasOwnProperty.call(object,key));// betterconsthas=Object.prototype.hasOwnProperty;// 在模块作用域内做一次缓存。console.log(has.call(object,key));// bestconsole.log(Object.hasOwn(object,key));// 只能在支持 ES2022 的浏览器中使用/* or */importhasfrom'has';// https://www.npmjs.com/package/hasconsole.log(has(object,key));/* or */console.log(Object.hasOwn(object,key));// https://www.npmjs.com/package/object.hasown
- 3.8 对象浅拷贝时,更推荐使用扩展运算符(即
...运算符),而不是Object.assign。获取对象指定的几个属性时,用对象的 rest 解构运算符(即...运算符)更好。eslint:prefer-object-spread- 这一段不太好翻译出来, 大家看下面的例子就懂了。^.^
// very badconstoriginal={a: 1,b: 2};constcopy=Object.assign(original,{c: 3});// 改了 `original` ಠ_ಠdeletecopy.a;// so does this// badconstoriginal={a: 1,b: 2};constcopy=Object.assign({},original,{c: 3});// copy => { a: 1, b: 2, c: 3 }// good es6 扩展运算符 ...constoriginal={a: 1,b: 2};// 浅拷贝constcopy={ ...original,c: 3};// copy => { a: 1, b: 2, c: 3 }// rest 解构运算符const{ a, ...noA}=copy;// noA => { b: 2, c: 3 }4.1 用字面量创建数组。eslint:
no-array-constructor// badconstitems=newArray();// goodconstitems=[];
4.2 用 Array#push 代替直接向数组中添加一个值。
constsomeStack=[];// badsomeStack[someStack.length]='abracadabra';// goodsomeStack.push('abracadabra');
4.3 用扩展运算符做数组浅拷贝,类似上面的对象浅拷贝。
// badconstlen=items.length;constitemsCopy=[];leti;for(i=0;i<len;i+=1){itemsCopy[i]=items[i];}// goodconstitemsCopy=[...items];
4.4 用
...运算符而不是Array.from来将一个可迭代的对象转换成数组。constfoo=document.querySelectorAll('.foo');// goodconstnodes=Array.from(foo);// bestconstnodes=[...foo];
4.5 用
Array.from将一个类数组对象转成一个数组。constarrLike={0: 'foo',1: 'bar',2: 'baz',length: 3};// badconstarr=Array.prototype.slice.call(arrLike);// goodconstarr=Array.from(arrLike);
4.6 用
Array.from而不是...运算符去做 map 遍历。 因为这样可以避免创建一个临时数组。// badconstbaz=[...foo].map(bar);// goodconstbaz=Array.from(foo,bar);
4.7 在数组方法的回调函数中使用 return 语句。如果函数体由一条返回一个表达式的语句组成,并且这个表达式没有副作用, 这个时候可以忽略 return,详见 8.2。eslint:
array-callback-return// good[1,2,3].map((x)=>{consty=x+1;returnx*y;});// good 函数只有一个语句[1,2,3].map((x)=>x+1);// bad - 没有返回值, 因为在第一次迭代后 acc 就变成 undefined 了[[0,1],[2,3],[4,5]].reduce((acc,item,index)=>{constflatten=acc.concat(item);});// good[[0,1],[2,3],[4,5]].reduce((acc,item,index)=>{constflatten=acc.concat(item);returnflatten;});// badinbox.filter((msg)=>{const{ subject, author }=msg;if(subject==='Mockingbird'){returnauthor==='Harper Lee';}else{returnfalse;}});// goodinbox.filter((msg)=>{const{ subject, author }=msg;if(subject==='Mockingbird'){returnauthor==='Harper Lee';}returnfalse;});
4.8 如果一个数组有很多行,在数组的
[后和]前断行。请看下面示例:// badconstarr=[[0,1],[2,3],[4,5],];constobjectInArray=[{id: 1,},{id: 2,}];constnumberInArray=[1,2,];// goodconstarr=[[0,1],[2,3],[4,5]];constobjectInArray=[{id: 1,},{id: 2,},];constnumberInArray=[1,2,];
5.1 用对象的解构赋值来获取和使用对象某个或多个属性值。eslint:
prefer-destructuring为什么? 解构使您不必为这些属性创建临时引用,并且避免重复引用对象。重复引用对象将造成代码重复、增加阅读次数、提高犯错概率。在一个块级作用域里,解构对象可以在同一个地方给解构字段赋值,而不需要读整个的代码块看它到底用了哪些字段。
// badfunctiongetFullName(user){constfirstName=user.firstName;constlastName=user.lastName;return`${firstName}${lastName}`;}// goodfunctiongetFullName(user){const{ firstName, lastName }=user;return`${firstName}${lastName}`;}// bestfunctiongetFullName({ firstName, lastName }){return`${firstName}${lastName}`;}
5.2 用数组解构。eslint:
prefer-destructuringconstarr=[1,2,3,4];// badconstfirst=arr[0];constsecond=arr[1];// goodconst[first,second]=arr;
5.3 多个返回值用对象的解构,而不是数组解构。
为什么?你可以在后期添加新的属性或者变换变量的顺序而不会破坏原有的引用。
// badfunctionprocessInput(input){// 然后就是见证奇迹的时刻return[left,right,top,bottom];}// 调用者需要想一想返回值的顺序const[left,__,top]=processInput(input);// goodfunctionprocessInput(input){// oops,奇迹又发生了return{ left, right, top, bottom };}// 调用者只需要选择他想用的值就好了const{ left, top }=processInput(input);
6.1 字符串应使用单引号
''。eslint:quotes// badconstname="Capt. Janeway";// bad - 模板字符串应该包含插入文字或换行constname=`Capt. Janeway`;// goodconstname='Capt. Janeway';
6.2 超过 100 个字符的字符串不应该用字符串连接成多行。
为什么?字符串折行增加编写难度且不易被搜索。
// badconsterrorMessage='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.';// badconsterrorMessage='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.';// goodconsterrorMessage='This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
6.3 当需要动态生成字符串时,使用模板字符串而不是字符串拼接。eslint:
prefer-templatetemplate-curly-spacing为什么?模板字符串更具可读性、多行语法更简洁以及更方便插入变量到字符串里头。
// badfunctionsayHi(name){return'How are you, '+name+'?';}// badfunctionsayHi(name){return['How are you, ',name,'?'].join();}// badfunctionsayHi(name){return`How are you, ${name}?`;}// goodfunctionsayHi(name){return`How are you, ${name}?`;}
6.5 不要使用不必要的转义字符。eslint:
no-useless-escape为什么?反斜线可读性差,因此仅当必要时才使用它。
// badconstfoo='\'this\' \i\s \"quoted\"';// goodconstfoo='\'this\' is "quoted"';//bestconstfoo=`my name is '${name}'`;
7.1 使用命名函数表达式而不是函数声明。eslint:
func-stylefunc-names函数表达式: const func = function () {}
函数声明: function func() {}
为什么?函数声明会发生提升,这意味着在一个文件里函数很容易在其被定义之前就被引用了。这样伤害了代码可读性和可维护性。如果你发现一个函数又大又复杂,且这个函数妨碍了这个文件其他部分的理解性,你应当单独把这个函数提取成一个单独的模块。不管这个名字是不是由一个确定的变量推断出来的,别忘了给表达式清晰的命名(这在现代浏览器和类似 babel 编译器中很常见)。这消除了由匿名函数在错误调用栈产生的所有假设。 (讨论)
译者注:这一段可能不是很好理解,简单来说就是使用函数声明会发生提升(即在函数被声明之前就可以使用);使用匿名函数会导致报错难以定位错误。常见错误范例这一段英文原文在这。
// badfunctionfoo(){// ...}// badconstfoo=function(){// ...};// good// lexical name distinguished from the variable-referenced invocation(s)// 函数表达式名和声明的函数名是不一样的constshort=functionlongUniqueMoreDescriptiveLexicalFoo(){// ...};
7.2 把立即执行函数包裹在圆括号里。eslint:
wrap-iife立即执行函数:Immediately Invoked Function expression = IIFE。 为什么?一个立即调用的函数表达式是一个单元 - 把它和它的调用者(圆括号)包裹起来,使代码读起来更清晰。 另外,在模块化世界里,你几乎用不着 IIFE。
// immediately-invoked function expression (IIFE)(function(){console.log('Welcome to the Internet. Please follow me.');}());
- 7.3 不要在非函数块(
if、while等)内声明函数。把这个函数分配给一个变量。浏览器会允许你这样做,但不同浏览器的解析方式不同,这是一个坏消息。eslint:no-loop-func
7.4注意:ECMA-262 中对块(
block)的定义是: 一系列的语句。但是函数声明不是一个语句, 函数表达式是一个语句。// badif(currentUser){functiontest(){console.log('Nope.');}}// goodlettest;if(currentUser){test=()=>{console.log('Yup.');};}
7.5 不要用
arguments命名参数。他的优先级高于每个函数作用域自带的arguments对象,这会导致函数自带的arguments值被覆盖。// badfunctionfoo(name,options,arguments){// ...}// goodfunctionfoo(name,options,args){// ...}
7.6 不要使用
arguments,用收集参数语法...代替。eslint:prefer-rest-params为什么?
...明确你想用哪个参数。而且收集参数是真数组,而不是类似数组的arguments。// badfunctionconcatenateAll(){constargs=Array.prototype.slice.call(arguments);returnargs.join('');}// goodfunctionconcatenateAll(...args){returnargs.join('');}
7.7 用默认参数语法而不是在函数里对参数重新赋值。
// really badfunctionhandleThings(opts){// 不!我们不该修改 arguments// 第二:如果 opts 的值为 false, 它会被赋值为 {}// 虽然你想这么写,但是这个会带来一些微妙的 bug。opts=opts||{};// ...}// still badfunctionhandleThings(opts){if(opts===void0){opts={};}// ...}// goodfunctionhandleThings(opts={}){// ...}
7.8 避免默认参数的副作用。
为什么?他会令人迷惑不解,比如下面这个,a 到底等于几,这个需要想一下。
varb=1;// badfunctioncount(a=b++){console.log(a);}count();// 1count();// 2count(3);// 3count();// 3
7.9 把默认参数赋值放在最后。eslint:
default-param-last// badfunctionhandleThings(opts={},name){// ...}// goodfunctionhandleThings(name,opts={}){// ...}
7.10 不要用函数构造器创建函数。eslint:
no-new-func为什么?以这种方式创建函数将类似于字符串 eval(),存在漏洞。
// badconstadd=newFunction('a','b','return a + b');// still badconstsubtract=Function('a','b','return a - b');
7.11 函数定义部分要有空格。eslint:
space-before-function-parenspace-before-blocks为什么?统一性好,而且在你添加/删除一个名字的时候不需要添加/删除空格。
// badconstf=function(){};constg=function(){};consth=function(){};// goodconstx=function(){};consty=functiona(){};
7.12 不要修改参数. eslint:
no-param-reassign为什么?操作参数对象对原始调用者会导致意想不到的副作用。就是不要改参数的数据结构,保留参数原始值和数据结构。
// badfunctionf1(obj){obj.key=1;};// goodfunctionf2(obj){constkey=Object.prototype.hasOwnProperty.call(obj,'key') ? obj.key : 1;};
7.13 不要对参数重新赋值。eslint:
no-param-reassign为什么?参数重新赋值会导致意外行为,尤其是对
arguments。这也会导致优化问题,特别是在 V8 引擎里。// badfunctionf1(a){a=1;// ...}functionf2(a){if(!a){a=1;}// ...}// goodfunctionf3(a){constb=a||1;// ...}functionf4(a=1){// ...}
7.14 使用拓展运算符调用多参数的函数。eslint:
prefer-spread为什么?这样更清晰,你不必提供上下文(即指定 this 值),而且你不能轻易地用
apply来组成new。// badconstx=[1,2,3,4,5];console.log.apply(console,x);// goodconstx=[1,2,3,4,5];console.log(...x);// badnew(Function.prototype.bind.apply(Date,[null,2016,8,5]));// goodnewDate(...[2016,8,5]);
7.15 调用或者编写一个包含多个参数的函数的缩进,应该像这个指南里的其他多行代码写法一样——即每行只包含一个参数,每行逗号结尾。
// badfunctionfoo(bar,baz,quux){// ...}// good 缩进不要太过分functionfoo(bar,baz,quux,){// ...}// badconsole.log(foo,bar,baz);// goodconsole.log(foo,bar,baz,);
8.1 当你一定要用函数表达式(在回调函数里)的时候,使用箭头函数。 eslint:
prefer-arrow-callback,arrow-spacing为什么?箭头函数中的
this与定义该函数的上下文中的this一致,这通常才是你想要的。而且箭头函数是更简洁的语法。什么时候不用箭头函数:如果你的函数逻辑较复杂,你应该把它单独写入一个命名函数里头。
// bad[1,2,3].map(function(x){consty=x+1;returnx*y;});// good[1,2,3].map((x)=>{consty=x+1;returnx*y;});
8.2 如果函数体由一个没有副作用的 表达式 语句组成,删除大括号和 return。否则,使用大括号和
return语句。 eslint:arrow-parens,arrow-body-style为什么?语法糖,当多个函数链在一起的时候好读。
// bad map 没有 return[1,2,3].map((number)=>{constnextNumber=number+1;`A string containing the ${nextNumber}.`;});// good[1,2,3].map((number)=>`A string containing the ${number+1}.`);// good[1,2,3].map((number)=>{constnextNumber=number+1;return`A string containing the ${nextNumber}.`;});// good[1,2,3].map((number,index)=>({[index]: number,}));// 没有明显的存在副作用的 return 语句functionfoo(callback){constval=callback();if(val===true){// 当 callback 返回 true 时在这里执行}}letbool=false;// badfoo(()=>bool=true);// goodfoo(()=>{bool=true;});
8.3 如果表达式涉及多行,把他包裹在圆括号里以提高可读性。
为什么?这样能清晰地显示函数的开始位置和结束位置。
// bad['get','post','put'].map((httpMethod)=>Object.prototype.hasOwnProperty.call(httpMagicObjectWithAVeryLongName,httpMethod));// good['get','post','put'].map((httpMethod)=>(Object.prototype.hasOwnProperty.call(httpMagicObjectWithAVeryLongName,httpMethod)));
8.4 在箭头函数参数两头,总是使用小括号包裹住参数,这样做使代码更清晰且一致. eslint:
arrow-parens为什么?当你想要添加或删除参数时改动最小。
// bad[1,2,3].map(x=>x*x);// good[1,2,3].map((x)=>x*x);// bad[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!`));// 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=>{consty=x+1;returnx*y;});// good[1,2,3].map((x)=>{consty=x+1;returnx*y;});
8.5 避免箭头函数(
=>)和比较操作符(<=,>=)混淆. eslint:no-confusing-arrow// badconstitemHeight=(item)=>item.height<=256 ? item.largeSize : item.smallSize;// badconstitemHeight=(item)=>item.height>=256 ? item.largeSize : item.smallSize;// goodconstitemHeight=(item)=>(item.height<=256 ? item.largeSize : item.smallSize);// goodconstitemHeight=(item)=>{const{ height, largeSize, smallSize }=item;returnheight<=256 ? largeSize : smallSize;};
8.6 使箭头函数体有一个清晰的返回。 eslint:
implicit-arrow-linebreak// bad(foo)=>bar;(foo)=>(bar);// good(foo)=>bar;(foo)=>(bar);(foo)=>(bar)
9.1 使用
class语法。避免直接操作prototype。为什么?
class语法更简洁更易理解。// badfunctionQueue(contents=[]){this.queue=[...contents];}Queue.prototype.pop=function(){constvalue=this.queue[0];this.queue.splice(0,1);returnvalue;};// goodclassQueue{constructor(contents=[]){this.queue=[...contents];}pop(){constvalue=this.queue[0];this.queue.splice(0,1);returnvalue;}}
9.2 用
extends实现继承。为什么?它是一种内置的方法来继承原型功能而不破坏
instanceof。// badconstinherits=require('inherits');functionPeekableQueue(contents){Queue.apply(this,contents);}inherits(PeekableQueue,Queue);PeekableQueue.prototype.peek=function(){returnthis.queue[0];}// goodclassPeekableQueueextendsQueue{peek(){returnthis.queue[0];}}
9.3 方法可以返回
this来实现链式调用。// badJedi.prototype.jump=function(){this.jumping=true;returntrue;};Jedi.prototype.setHeight=function(height){this.height=height;};constluke=newJedi();luke.jump();// => trueluke.setHeight(20);// => undefined// goodclassJedi{jump(){this.jumping=true;returnthis;}setHeight(height){this.height=height;returnthis;}}constluke=newJedi();luke.jump().setHeight(20);
9.4 自己写
toString()方法是可以的,但需要保证它可以正常工作且没有副作用。classJedi{constructor(options={}){this.name=options.name||'no name';}getName(){returnthis.name;}toString(){return`Jedi - ${this.getName()}`;}}
9.5 如果没有特别定义,类有默认的构造方法。一个空的构造函数或只是代表父类的构造函数是不需要写的。 eslint:
no-useless-constructor// badclassJedi{constructor(){}getName(){returnthis.name;}}// badclassReyextendsJedi{// 这种构造函数是不需要写的constructor(...args){super(...args);}}// goodclassReyextendsJedi{constructor(...args){super(...args);this.name='Rey';}}
9.6 避免重复定义类成员。eslint:
no-dupe-class-members为什么?重复定义类成员只会使用最后一个被定义的 —— 重复本身也是一个 bug.
// badclassFoo{bar(){return1;}bar(){return2;}}// goodclassFoo{bar(){return1;}}// goodclassFoo{bar(){return2;}}
9.7 除非外部库或框架需要使用特定的非静态方法,否则类方法应该使用
this或被写成静态方法。 作为一个实例方法表明它应该根据实例的属性有不同的行为。eslint:class-methods-use-this// badclassFoo{bar(){console.log('bar');}}// good - this 被使用了classFoo{bar(){console.log(this.bar);}}// good - constructor 不一定要使用 thisclassFoo{constructor(){// ...}}// good - 静态方法不需要使用 thisclassFoo{staticbar(){console.log('bar');}}
10.1 使用(
import/export)模块而不是非标准的模块系统。你可以随时转到你喜欢的模块系统。为什么?模块化是未来,让我们现在就开启未来吧。
// badconstAirbnbStyleGuide=require('./AirbnbStyleGuide');module.exports=AirbnbStyleGuide.es6;// okimportAirbnbStyleGuidefrom'./AirbnbStyleGuide';exportdefaultAirbnbStyleGuide.es6;// bestimport{es6}from'./AirbnbStyleGuide';exportdefaultes6;
10.2 不要用
import通配符, 即*这种方式。为什么?这确保你有单个默认的导出。
// badimport*asAirbnbStyleGuidefrom'./AirbnbStyleGuide';// goodimportAirbnbStyleGuidefrom'./AirbnbStyleGuide';
10.3 不要直接从
import中直接export。为什么?虽然只写一行很简洁,但是使用明确
import和明确的export来保证一致性。// bad// filename es6.jsexport{es6asdefault}from'./AirbnbStyleGuide';// good// filename es6.jsimport{es6}from'./AirbnbStyleGuide';exportdefaultes6;
10.4 一个路径只
import一次。eslint:no-duplicate-imports为什么?多行导入同一路径将使代码变得难以维护。
// badimportfoofrom'foo';// … 其他导入 … //import{named1,named2}from'foo';// goodimportfoo,{named1,named2}from'foo';// goodimportfoo,{named1,named2,}from'foo';
10.5 不要导出可变的东西。eslint:
import/no-mutable-exports为什么?变化通常都是需要避免,特别是当你要输出可变的绑定。虽然在某些场景下可能需要这种技术,但总的来说应该导出常量。
// badletfoo=3;export{foo}// goodconstfoo=3;export{foo}
10.6 在一个单一导出模块里,用
export default更好。eslint:import/prefer-default-export为什么?鼓励使用更多文件,每个文件只导出一次,这样可读性和可维护性更好。
// badexportfunctionfoo(){}// goodexportdefaultfunctionfoo(){}
10.7 把
import放在其他所有语句之前。eslint:import/first为什么?因为
import会被提升到代码最前面运行,因此将他们放在最前面以防止发生意外行为。// badimportfoofrom'foo';foo.init();importbarfrom'bar';// goodimportfoofrom'foo';importbarfrom'bar';foo.init();
10.8 多行
import应该缩进,就像多行数组和对象字面量一样。eslint:object-curly-newline为什么?花括号与样式指南中每个其他花括号块遵循相同的缩进规则,逗号也是。
// badimport{longNameA,longNameB,longNameC,longNameD,longNameE}from'path';// goodimport{longNameA,longNameB,longNameC,longNameD,longNameE,}from'path';
10.9 在
import语句里不允许 Webpack loader 语法。eslint:import/no-webpack-loader-syntax为什么?一旦用 Webpack 语法在 import 里会把代码耦合到模块绑定器。最好是在
webpack.config.js里写 webpack loader 语法// badimportfooSassfrom'css!sass!foo.scss';importbarCssfrom'style!css!bar.css';// goodimportfooSassfrom'foo.scss';importbarCssfrom'bar.css';
10.10 import JavaScript文件不用包含扩展名 eslint:
import/extensions为什么? 使用扩展名重构不友好,而且让模块使用者去了解模块的实现细节是不合适的。
// badimportfoofrom'./foo.js';importbarfrom'./bar.jsx';importbazfrom'./baz/index.jsx';// goodimportfoofrom'./foo';importbarfrom'./bar';importbazfrom'./baz';
11.1 不要用迭代器。使用 JavaScript 高级函数代替
for-in、for-of。eslint:no-iteratorno-restricted-syntax为什么?这强调了我们不可变的规则。 处理返回值的纯函数比处理副作用更容易。
用数组的这些迭代方法:
map()/every()/filter()/find()/findIndex()/reduce()/some()/ ... , 用对象的这些方法Object.keys()/Object.values()/Object.entries()去产生一个数组,这样你就能去遍历对象了。constnumbers=[1,2,3,4,5];// badletsum=0;for(letnumofnumbers){sum+=num;}sum===15;// goodletsum=0;numbers.forEach((num)=>sum+=num);sum===15;// best (use the functional force)constsum=numbers.reduce((total,num)=>total+num,0);sum===15;// badconstincreasedByOne=[];for(leti=0;i<numbers.length;i++){increasedByOne.push(numbers[i]+1);}// goodconstincreasedByOne=[];numbers.forEach((num)=>{increasedByOne.push(num+1);});// best (keeping it functional)constincreasedByOne=numbers.map((num)=>num+1);
11.2 现在暂时不要使用生成器。
为什么?生成器目前不能很好地转换为 ES5 语法。
11.3 如果你一定要用生成器,或者你忽略 我们的建议,请确保它们的函数标志空格是得当的。eslint:
generator-star-spacing为什么?
function和*是同一概念关键字 -*不是function的修饰符,function*是一个和function不一样的独特结构。// badfunction*foo(){// ...}// badconstbar=function*(){// ...}// badconstbaz=function*(){// ...}// badconstquux=function*(){// ...}// badfunction*foo(){// ...}// badfunction*foo(){// ...}// very badfunction*foo(){// ...}// very badconstwat=function*(){// ...}// goodfunction*foo(){// ...}// goodconstfoo=function*(){// ...}
12.1 访问属性时使用点符号。eslint:
dot-notationconstluke={jedi: true,age: 28,};// badconstisJedi=luke['jedi'];// goodconstisJedi=luke.jedi;
12.2 当使用变量获取属性时用方括号
[]。constluke={jedi: true,age: 28,};functiongetProp(prop){returnluke[prop];}constisJedi=getProp('jedi');
12.3 做幂运算时用幂操作符
**。eslint:prefer-exponentiation-operator。// badconstbinary=Math.pow(2,10);// goodconstbinary=2**10;
13.1 使用
const或let声明变量。不这样做会导致全局变量。我们想要避免污染全局命名空间。地球超人也这样警告我们(译者注:可能是一个冷笑话)。 eslint:no-undefprefer-const// badsuperPower=newSuperPower();// goodconstsuperPower=newSuperPower();
13.2 为每个变量声明都用一个
const或let。eslint:one-var为什么?这种方式很容易去声明新的变量,你不用去考虑把
;调换成,,或者引入一个只有标点的不同的变化(译者注:这里说的应该是在 Git 提交代码时显示的变化)。这种做法也可以是你在调试的时候单步每个声明语句,而不是一下跳过所有声明。// badconstitems=getItems(),goSportsTeam=true,dragonball='z';// bad// (与前面的比较,找一找错误)constitems=getItems(),goSportsTeam=true;dragonball='z';// goodconstitems=getItems();constgoSportsTeam=true;constdragonball='z';
13.3 把
const和let分别放一起。为什么?在你需要分配一个新的变量,而这个变量依赖之前分配过的变量的时候,这种做法是有帮助的。
// badleti,len,dragonball,items=getItems(),goSportsTeam=true;// badleti;constitems=getItems();letdragonball;constgoSportsTeam=true;letlen;// goodconstgoSportsTeam=true;constitems=getItems();letdragonball;leti;letlength;
13.4 在你需要的地方声明变量,但是要放在合理的位置。
为什么?
let和const都是块级作用域而不是函数级作用域。// bad - 不必要的函数调用。functioncheckName(hasName){constname=getName();if(hasName==='test'){returnfalse;}if(name==='test'){this.setName('');returnfalse;}returnname;}// goodfunctioncheckName(hasName){if(hasName==='test'){returnfalse;}// 在需要的时候分配constname=getName();if(name==='test'){this.setName('');returnfalse;}returnname;}
13.5 不要使用链式声明变量。 eslint:
no-multi-assign为什么?链式声明变量会创建隐式全局变量。
// bad(functionexample(){// JavaScript 将这一段解释为// let a = ( b = ( c = 1 ) );// let 只对变量 a 起作用; 变量 b 和 c 都变成了全局变量leta=b=c=1;}());console.log(a);// undefinedconsole.log(b);// 1console.log(c);// 1// good(functionexample(){leta=1;letb=a;letc=a;}());console.log(a);// undefinedconsole.log(b);// undefinedconsole.log(c);// undefined// `const` 也是如此
13.6 不要使用一元自增自减运算符(
++,--). eslintno-plusplus为什么?根据 eslint 文档,一元增量和减量语句受到自动分号插入的影响,并且可能会导致应用程序中的值递增或递减的静默错误。 使用
num + = 1而不是num ++或num ++语句也是含义清晰的。 禁止一元增量和减量语句还会阻止您无意地预增/预减值,这也会导致程序出现意外行为。// badconstarray=[1,2,3];letnum=1;num++;--num;letsum=0;lettruthyCount=0;for(leti=0;i<array.length;i++){letvalue=array[i];sum+=value;if(value){truthyCount++;}}// goodconstarray=[1,2,3];letnum=1;num+=1;num-=1;constsum=array.reduce((a,b)=>a+b,0);consttruthyCount=array.filter(Boolean).length;
13.7 在赋值的时候避免在
=前/后换行。 如果你的赋值语句超出max-len,那就用小括号把这个值包起来再换行。eslintoperator-linebreak.为什么?在
=附近换行容易混淆这个赋值语句。// badconstfoo=superLongLongLongLongLongLongLongLongFunctionName();// badconstfoo='superLongLongLongLongLongLongLongLongString';// goodconstfoo=(superLongLongLongLongLongLongLongLongFunctionName());// goodconstfoo='superLongLongLongLongLongLongLongLongString';
13.8 不允许有未使用的变量。eslint:
no-unused-vars为什么?一个声明了但未使用的变量更像是由于重构未完成产生的错误。这种在代码中出现的变量会使阅读者迷惑。
// badconstsome_unused_var=42;// 写了没用lety=10;y=5;// 变量改了自己的值,也没有用这个变量letz=0;z=z+1;// 参数定义了但未使用functiongetX(x,y){returnx;}// goodfunctiongetXPlusY(x,y){returnx+y;}constx=1;consty=a+2;alert(getXPlusY(x,y));// 'type' 即使没有使用也可以可以被忽略, 因为这个有一个 rest 取值的属性。// 这是从对象中抽取一个忽略特殊字段的对象的一种形式const{ type, ...coords}=data;// 'coords' 现在就是一个没有 'type' 属性的 'data' 对象
14.1
var声明会被提前到离他最近的作用域的最前面,但是它的赋值语句并没有提前。const和let被赋予了新的概念 暂时性死区 (TDZ)。 重要的是要知道为什么 typeof 不再安全。// 我们知道这个不会工作,假设没有定义全局的 notDefinedfunctionexample(){console.log(notDefined);// => throws a ReferenceError}// 在你引用的地方之后声明一个变量,他会正常输出是因为变量提升。// 注意: declaredButNotAssigned 的值 true 没有被提升。functionexample(){console.log(declaredButNotAssigned);// => undefinedvardeclaredButNotAssigned=true;}// 解释器把变量声明提升到作用域最前面,// 可以重写成如下例子, 二者意义相同。functionexample(){letdeclaredButNotAssigned;console.log(declaredButNotAssigned);// => undefineddeclaredButNotAssigned=true;}// 用 const,let就不一样了。functionexample(){console.log(declaredButNotAssigned);// => throws a ReferenceErrorconsole.log(typeofdeclaredButNotAssigned);// => throws a ReferenceErrorconstdeclaredButNotAssigned=true;}
14.2 匿名函数表达式和
var情况相同。functionexample(){console.log(anonymous);// => undefinedanonymous();// => TypeError anonymous is not a function// 译者注,不管后面是函数、数字还是字符串,都是一样的,总结就是实际代码中最好不要用 var。varanonymous=function(){console.log('anonymous function expression');};}
14.3 已命名函数表达式提升他的变量名,不是函数名或函数体。
functionexample(){console.log(named);// => undefinednamed();// => TypeError named is not a functionsuperPower();// => ReferenceError superPower is not definedvarnamed=functionsuperPower(){console.log('Flying');};}// 函数名和变量名一样是也如此。functionexample(){console.log(named);// => undefinednamed();// => TypeError named is not a functionvarnamed=functionnamed(){console.log('named');};}
14.4 函数声明则提升了函数名和函数体。
functionexample(){superPower();// => FlyingfunctionsuperPower(){console.log('Flying');}}
14.5 变量、类、函数都应该在使用前定义。 eslint:
no-use-before-define为什么? 当变量、类或者函数在使用处之后定义,这让阅读者很难想到这个函数引用自何处。 对于读者在遇到某个事物之前,如果能知道这个事物的来源(不论是在文件中定义还是从别的模块引用),理解起来都会清晰很多。
// 不好的// 变量 a 使用出现在定义之前console.log(a);// 这样会导致 undefined,虽然变量声明被提升了, 但 a 初始化复制却还没执行vara=10;// 函数 fun 使用出现在定义之前fun();functionfun(){}// 类 A 使用出现在定义之前newA();// 引用错误: 无法在 A 初始化之前访问它classA{}// `let` 和 `const` 被提升, 但是他们没有初始化变量值// 变量 a、 b 都被放在了 JavaScript 的暂时性死区 (Temporal Dead Zone, 指在变量被声明之前无法访问它的现象)。console.log(a);// 引用错误: 无法在 a 初始化之前访问它console.log(b);// 引用错误: 无法在 b 初始化之前访问它leta=10;constb=5;// 好的vara=10;console.log(a);// 10functionfun(){}fun();classA{}newA();leta=10;constb=5;console.log(a);// 10console.log(b);// 5
详情请见 JavaScript Scoping & Hoisting by Ben Cherry.
15.2 条件语句如
if语句使用强制ToBoolean抽象方法来计算它们的表达式,并且始终遵循以下简单规则:- Objects 计算成 true
- Undefined 计算成 false
- Null 计算成 false
- Booleans 计算成 the value of the boolean
- Numbers
- +0, -0, or NaN 计算成 false
- 其他 true
- Strings
''计算成 false- 其他 true
if([0]&&[]){// true// 数组(即使是空数组)是对象,对象会计算成 true}
15.3 布尔值要用缩写,而字符串和数字要明确使用比较操作符。
// badif(isValid===true){// ...}// goodif(isValid){// ...}// badif(name){// ...}// goodif(name!==''){// ...}// badif(collection.length){// ...}// goodif(collection.length>0){// ...}
- 15.4 更多信息请见 Angus Croll 的 Truth, Equality, and JavaScript。
15.5 在
case和default分句里用大括号创建一块包含词法声明的区域(例如:let、const、function和class)。eslint rules:no-case-declarations.为什么?词法声明在整个
switch的代码块里都可见,但是只有当其被分配后才会初始化,仅当这个case被执行时才被初始化。当多个case分句试图定义同一个对象时就会出现问题。// badswitch(foo){case1: letx=1;break;case2: consty=2;break;case3: functionf(){// ...}break;default: classC{}}// goodswitch(foo){case1: {letx=1;break;}case2: {consty=2;break;}case3: {functionf(){// ...}break;}case4: bar();break;default: {classC{}}}
15.6 三元表达式不应该嵌套,通常是单行表达式。eslint rules:
no-nested-ternary// badconstfoo=maybe1>maybe2 ? "bar" : value1>value2 ? "baz" : null;// betterconstmaybeNull=value1>value2 ? 'baz' : null;constfoo=maybe1>maybe2 ? 'bar' : maybeNull;// bestconstmaybeNull=value1>value2 ? 'baz' : null;constfoo=maybe1>maybe2 ? 'bar' : maybeNull;
15.7 避免不必要的三元表达式。eslint rules:
no-unneeded-ternary// badconstfoo=a ? a : b;constbar=c ? true : false;constbaz=c ? false : true;constquux=a!=null ? a : b;// goodconstfoo=a||b;constbar=!!c;constbaz=!c;constquux=a??b;
15.8 用圆括号来组合多种操作符。唯一里的例外就是像
+,-, 和**这种优先级容易理解的运算符。我们还是建议把/*放到小括号里, 因为他们混用的时候优先级容易有歧义。 eslint:no-mixed-operators为什么?这提高了可读性,并且明确了开发者的意图。
// badconstfoo=a&&b<0||c>0||d+1===0;// badconstbar=a**b-5%d;// bad// 别人会陷入(a || b) && c 的迷惑中if(a||b&&c){returnd;}// badconstbar=a+b/c*d;// goodconstfoo=(a&&b<0)||c>0||(d+1===0);// goodconstbar=(a**b)-(5%d);// goodif(a||(b&&c)){returnd;}// goodconstbar=a+(b/c)*d;
15.9 (
??) 是一个逻辑运算符, 当运算符左侧是 null 或 undefined 时返回右侧的值, 否则返回左侧值。为什么? (
??)这个运算符通过精确区分null/undefined和其他"falsy"值,从而增强了代码的清晰度和可预测性。// 不好的constvalue=0??'default';// returns 0, not 'default'// 不好的constvalue=''??'default';// returns '', not 'default'// 好的constvalue=null??'default';// returns 'default'// 好的constuser={name: 'John',age: null};constage=user.age??18;// returns 18
16.1 用大括号包裹多行代码块。 eslint:
nonblock-statement-body-position// badif(test)returnfalse;// goodif(test)returnfalse;// goodif(test){returnfalse;}// badfunctionfoo(){returnfalse;}// goodfunctionbar(){returnfalse;}
16.2
if表达式的else和if的右大括号在一行。eslint:brace-style// badif(test){thing1();thing2();}else{thing3();}// goodif(test){thing1();thing2();}else{thing3();}
16.3 如果
if语句中总是需要用return返回,那后续的else就不需要写了。if块中包含return, 它后面的else if块中也包含了return, 这个时候就可以把return分到多个if语句块中。 eslint:no-else-return// badfunctionfoo(){if(x){returnx;}else{returny;}}// badfunctioncats(){if(x){returnx;}elseif(y){returny;}}// badfunctiondogs(){if(x){returnx;}else{if(y){returny;}}}// goodfunctionfoo(){if(x){returnx;}returny;}// goodfunctioncats(){if(x){returnx;}if(y){returny;}}// goodfunctiondogs(x){if(x){if(z){returny;}}else{returnz;}}
17.1 当你的控制语句(
if,while等)太长或者超过最大长度限制的时候,把每一个(组)判断条件放在单独一行里。逻辑操作符放在行首。为什么?把逻辑操作符放在行首是让操作符的对齐方式和链式函数保持一致。这提高了可读性,也让复杂逻辑更清晰。
// badif((foo===123||bar==='abc')&&doesItLookGoodWhenItBecomesThatLong()&&isThisReallyHappening()){thing1();}// badif(foo===123&&bar==='abc'){thing1();}// badif(foo===123&&bar==='abc'){thing1();}// badif(foo===123&&bar==='abc'){thing1();}// goodif(foo===123&&bar==='abc'){thing1();}// goodif((foo===123||bar==='abc')&&doesItLookGoodWhenItBecomesThatLong()&&isThisReallyHappening()){thing1();}// goodif(foo===123&&bar==='abc'){thing1();}
17.2 不要用选择操作符代替控制语句。
// bad!isRunning&&startRunning();// goodif(!isRunning){startRunning();}
18.1 多行注释用
/** ... */。// bad// make() returns a new element// based on the passed in tag name//// @param {String} tag// @return {Element} elementfunctionmake(tag){// ...returnelement;}// good/** * make() returns a new element * based on the passed-in tag name */functionmake(tag){// ...returnelement;}
18.2 单行注释用
//,将单行注释放在被注释区域上面。如果注释不是在第一行,那么注释前面就空一行。// badconstactive=true;// is current tab// good// is current tabconstactive=true;// badfunctiongetType(){console.log('fetching type...');// set the default type to 'no type'consttype=this._type||'no type';returntype;}// goodfunctiongetType(){console.log('fetching type...');// set the default type to 'no type'consttype=this._type||'no type';returntype;}// also goodfunctiongetType(){// set the default type to 'no type'consttype=this._type||'no type';returntype;}
18.3 所有注释开头空一格,方便阅读。eslint:
spaced-comment// bad//is current tabconstactive=true;// good// is current tabconstactive=true;// bad/** *make() returns a new element *based on the passed-in tag name */functionmake(tag){// ...returnelement;}// good/** * make() returns a new element * based on the passed-in tag name */functionmake(tag){// ...returnelement;}
- 18.4 在你的注释前使用
FIXME或TODO前缀,这有助于其他开发人员快速理解你指出的需要修复的问题, 或者您建议需要实现的问题的解决方案。 这些不同于常规注释,它们是有明确含义的。FIXME:需要修复这个问题或TODO:需要实现的功能。
18.5 用
// FIXME:给问题做注释。classCalculatorextendsAbacus{constructor(){super();// FIXME: shouldn't use a global heretotal=0;}}
18.6 用
// TODO:去注释问题的解决方案。classCalculatorextendsAbacus{constructor(){super();// TODO: total should be configurable by an options paramthis.total=0;}}
19.1 一个缩进使用两个空格。eslint:
indent// badfunctionfoo(){∙∙∙∙constname;}// badfunctionbar(){∙constname;}// goodfunctionbaz(){∙∙constname;}
19.2 在大括号前空一格。eslint:
space-before-blocks// badfunctiontest(){console.log('test');}// goodfunctiontest(){console.log('test');}// baddog.set('attr',{age: '1 year',breed: 'Bernese Mountain Dog',});// gooddog.set('attr',{age: '1 year',breed: 'Bernese Mountain Dog',});
19.3 在控制语句(
if,while等)的圆括号前空一格。在函数调用和定义时,参数列表和函数名之间不空格。 eslint:keyword-spacing// badif(isJedi){fight();}// goodif(isJedi){fight();}// badfunctionfight(){console.log('Swooosh!');}// goodfunctionfight(){console.log('Swooosh!');}
19.4 用空格来隔开运算符。eslint:
space-infix-ops// badconstx=y+5;// goodconstx=y+5;
// badimport{es6}from'./AirbnbStyleGuide';// ...exportdefaultes6;
// badimport{es6}from'./AirbnbStyleGuide';// ...exportdefaultes6;
// goodimport{es6}from'./AirbnbStyleGuide';// ...exportdefaultes6;↵
19.6 当出现长的方法链式调用时(>2个)用缩进。用点开头强调该行是一个方法调用,而不是一个新的语句。eslint:
newline-per-chained-callno-whitespace-before-property// bad$('#items').find('.selected').highlight().end().find('.open').updateCount();// bad$('#items').find('.selected').highlight().end().find('.open').updateCount();// good$('#items').find('.selected').highlight().end().find('.open').updateCount();// badconstleds=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);// goodconstleds=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);// goodconstleds=stage.selectAll('.led').data(data);constsvg=leds.enter().append('svg:svg');svg.classed('led',true).attr('width',(radius+margin)*2);constg=svg.append('svg:g');g.attr('transform',`translate(${radius+margin}, ${radius+margin})`).call(tron.led);
19.7 在一个代码块后下一条语句前空一行。
// badif(foo){returnbar;}returnbaz;// goodif(foo){returnbar;}returnbaz;// badconstobj={foo(){},bar(){},};returnobj;// goodconstobj={foo(){},bar(){},};returnobj;// badconstarr=[functionfoo(){},functionbar(){},];returnarr;// goodconstarr=[functionfoo(){},functionbar(){},];returnarr;
19.8 不要用空白行填充块。eslint:
padded-blocks// badfunctionbar(){console.log(foo);}// also badif(baz){console.log(quux);}else{console.log(foo);}// goodfunctionbar(){console.log(foo);}// goodif(baz){console.log(quux);}else{console.log(foo);}
19.9 不要在代码之间使用多个空白行填充。eslint:
no-multiple-empty-lines// badclassPerson{constructor(fullName,email,birthday){this.fullName=fullName;this.email=email;this.setAge(birthday);}setAge(birthday){consttoday=newDate();constage=this.getAge(today,birthday);this.age=age;}getAge(today,birthday){// ..}}// goodclassPerson{constructor(fullName,email,birthday){this.fullName=fullName;this.email=email;this.setAge(birthday);}setAge(birthday){consttoday=newDate();constage=getAge(today,birthday);this.age=age;}getAge(today,birthday){// ..}}
19.10 圆括号里不要加空格。eslint:
space-in-parens// badfunctionbar(foo){returnfoo;}// goodfunctionbar(foo){returnfoo;}// badif(foo){console.log(foo);}// goodif(foo){console.log(foo);}
19.11 方括号里不要加空格。 eslint:
array-bracket-spacing// badconstfoo=[1,2,3];console.log(foo[0]);// good,逗号分隔符后还是要空格的。constfoo=[1,2,3];console.log(foo[0]);
19.12 花括号里加空格 。eslint:
object-curly-spacing// badconstfoo={clark: 'kent'};// goodconstfoo={clark: 'kent'};
19.13 避免一行代码超过100个字符(包含空格)。注意:对于 上面,长字符串不受此规则限制,不应换行。 eslint:
max-len为什么?这样确保可读性和可维护性。
// badconstfoo=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.'));// goodconstfoo=jsonData&&jsonData.foo&&jsonData.foo.bar&&jsonData.foo.bar.baz&&jsonData.foo.bar.baz.quux&&jsonData.foo.bar.baz.quux.xyzzy;// betterconstfoo=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.14 作为语句的花括号内也要加空格 ——
{后和}前都需要空格。 eslint:block-spacing// badfunctionfoo(){returntrue;}if(foo){bar=0;}// goodfunctionfoo(){returntrue;}if(foo){bar=0;}
19.15
,前不要空格,,后需要空格。 eslint:comma-spacing// badconstfoo=1,bar=2;constarr=[1,2];// goodconstfoo=1,bar=2;constarr=[1,2];
19.16 花括号跟属性间要有空格,中括号跟属性间没有空格。 eslint:
computed-property-spacing译者注:以代码为准。
// badobj[foo]obj['foo']constx={[b]: a}obj[foo[bar]]// goodobj[foo]obj['foo']constx={[b]: a}obj[foo[bar]]
19.17 调用函数时,函数名和小括号之间不要空格。 eslint:
func-call-spacing// badfunc();func();// goodfunc();
19.18 在对象的字面量属性中,
key和value之间要有空格。 eslint:key-spacing// badconstobj={foo : 42};constobj2={foo:42};// goodconstobj={foo: 42};
- 19.19 行末不要空格。 eslint:
no-trailing-spaces
19.20 避免出现多个空行。 在文件末尾只允许空一行。文件开始处不要出现空行。eslint:
no-multiple-empty-lines// bad - multiple empty linesconstx=1;consty=2;// bad - 2+ newlines at end of fileconstx=1;consty=2;// bad - 1+ newline(s) at beginning of fileconstx=1;consty=2;// goodconstx=1;consty=2;
20.1 不要前置逗号。eslint:
comma-style// badconststory=[once,upon,aTime];// goodconststory=[once,upon,aTime,];// badconsthero={firstName: 'Ada',lastName: 'Lovelace',birthYear: 1815,superPower: 'computers'};// goodconsthero={firstName: 'Ada',lastName: 'Lovelace',birthYear: 1815,superPower: 'computers',};
20.2 额外结尾逗号: 要 eslint:
comma-dangle为什么?这使 git diffs 更简洁。此外,像Babel这样的转换器会删除转换代码中的额外的逗号,这意味着你不必担心旧版浏览器中的 结尾逗号问题。
// bad - 没有结尾逗号的 git diff const hero = { firstName: 'Florence', - lastName: 'Nightingale'+ lastName: 'Nightingale',+ inventorOf: ['coxcomb chart', 'modern nursing'] }; // good - 有结尾逗号的 git diff const hero = { firstName: 'Florence', lastName: 'Nightingale', + inventorOf: ['coxcomb chart', 'modern nursing'], };// badconsthero={firstName: 'Dana',lastName: 'Scully'};constheroes=['Batman','Superman'];// goodconsthero={firstName: 'Dana',lastName: 'Scully',};constheroes=['Batman','Superman',];// badfunctioncreateHero(firstName,lastName,inventorOf){// does nothing}// goodfunctioncreateHero(firstName,lastName,inventorOf,){// does nothing}// good (注意,逗号不应出现在使用了 ... 操作符后的参数后面)functioncreateHero(firstName,lastName,inventorOf, ...heroArgs){// does nothing}// badcreateHero(firstName,lastName,inventorOf);// goodcreateHero(firstName,lastName,inventorOf,);// good (注意,逗号不应出现在使用了 ... 操作符后的参数后面)createHero(firstName,lastName,inventorOf, ...heroArgs)
为什么?当 JavaScript 遇到没有分号结尾的一行,它会执行 自动插入分号 这一规则来决定行末是否加分号。如果 JavaScript 在你的断行里错误的插入了分号,就会出现一些古怪的行为。当新的功能加到JavaScript 里后, 这些规则会变得更复杂难懂。清晰的结束语句,并通过配置代码检查去检查没有带分号的地方可以帮助你防止这种错误。
// bad - 抛出异常constluke={}constleia={}[luke,leia].forEach((jedi)=>jedi.father='vader')// bad - 抛出异常constreaction='No! That’s impossible!'(asyncfunctionmeanwhileOnTheFalcon(){// 处理 `leia`, `lando`, `chewie`, `r2`, `c3p0`// ...}())// bad - 将返回 `undefined` 而不是下一行的值。由于 ASI,当 `return`单独出现在一行时,这种情况会一直出现。functionfoo(){return'search your feelings, you know it to be foo'}// goodconstluke={};constleia={};[luke,leia].forEach((jedi)=>{jedi.father='vader';});// goodconstreaction="No! That’s impossible!";(asyncfunctionmeanwhileOnTheFalcon(){// handle `leia`, `lando`, `chewie`, `r2`, `c3p0`// ...}());// goodfunctionfoo(){return'search your feelings, you know it to be foo';}
更多.
- 22.1 在语句开始执行强制类型转换。
22.2 字符串: eslint:
no-new-wrappers// => this.reviewScore = 9;// badconsttotalScore=newString(this.reviewScore);// typeof totalScore is "object" not "string"// badconsttotalScore=this.reviewScore+'';// 将会执行 this.reviewScore.valueOf()// badconsttotalScore=this.reviewScore.toString();// 不保证返回 string// goodconsttotalScore=String(this.reviewScore);
22.3 数字: 用
Number做类型转换,parseInt转换string应总是带上基数。 eslint:radix为什么?函数
parseInt会根据指定的基数将字符串转换为数字。字符串开头的空白字符将会被忽略,如果参数基数(第二个参数)为undefined或者0,除非字符串开头为0x或0X(十六进制),会默认假设为10。这个差异来自 ECMAScript 3,它不鼓励(但是允许)解释八进制。在 2013 年之前,一些实现不兼容这种行为。因为我们需要支持旧浏览器,所以应当始终指定进制。译者注:翻译的可能不是很好,总之使用
parseInt()时始终指定进制数(第二个参数)就可以了。constinputValue='4';// badconstval=newNumber(inputValue);// badconstval=+inputValue;// badconstval=inputValue>>0;// badconstval=parseInt(inputValue);// goodconstval=Number(inputValue);// goodconstval=parseInt(inputValue,10);
22.4 请在注释中解释为什么要用移位运算和你在做什么。无论你做什么狂野的事,比如由于
parseInt是你的性能瓶颈导致你一定要用移位运算。说明这个是因为 性能原因。// good/** * parseInt 是代码运行慢的原因 * 用 Bitshifting 将字符串转成数字使代码运行效率大幅提升 */constval=inputValue>>0;
22.5注意: 用移位运算要小心。数字是用 64-位表示的,但移位运算常常返回的是32为整形source)。移位运算对大于 32 位的整数会导致意外行为。Discussion. 最大的 32 位整数是 2,147,483,647:
2147483647>>0//=> 21474836472147483648>>0//=> -21474836482147483649>>0//=> -2147483647
22.6 布尔: eslint:
no-new-wrappersconstage=0;// badconsthasAge=newBoolean(age);// goodconsthasAge=Boolean(age);// bestconsthasAge=!!age;
23.2 用小驼峰命名法来命名你的对象、函数、实例。eslint:
camelcase// badconstOBJEcttsssss={};constthis_is_my_object={};functionc(){}// goodconstthisIsMyObject={};functionthisIsMyFunction(){}
23.3 用大驼峰命名法来命名类。eslint:
new-cap// badfunctionuser(options){this.name=options.name;}constbad=newuser({name: 'nope',});// goodclassUser{constructor(options){this.name=options.name;}}constgood=newUser({name: 'yup',});
23.4 不要用前置或后置下划线。eslint:
no-underscore-dangle为什么?JavaScript 没有私有属性或私有方法的概念。尽管前置下划线通常的概念上意味着私有,事实上,这些属性是完全公有的,因此这部分也是你的 API 的内容。这一概念可能会导致开发者误以为更改这个不会导致崩溃或者不需要测试。如果你想要什么东西变成私有,那就不要让它在这里出现。
// 不好的this.__firstName__='Panda';this.firstName_='Panda';this._firstName='Panda';// 好的this.firstName='Panda';// 好的, 在支持 WeakMaps 环境中可用// 见 https://compat-table.github.io/compat-table/es6/#test-WeakMapconstfirstNames=newWeakMap();firstNames.set(this,'Panda');
23.5 不要保存引用
this,用箭头函数或 函数绑定——Function#bind。// badfunctionfoo(){constself=this;returnfunction(){console.log(self);};}// badfunctionfoo(){constthat=this;returnfunction(){console.log(that);};}// goodfunctionfoo(){return()=>{console.log(this);};}
23.6
export default导出模块A,则这个文件名也叫A.*,import时候的参数也叫A。 大小写完全一致。// file 1 contentsclassCheckBox{// ...}exportdefaultCheckBox;// file 2 contentsexportdefaultfunctionfortyTwo(){return42;}// file 3 contentsexportdefaultfunctioninsideDirectory(){}// in some other file// badimportCheckBoxfrom'./checkBox';// PascalCase import/export, camelCase filenameimportFortyTwofrom'./FortyTwo';// PascalCase import/filename, camelCase exportimportInsideDirectoryfrom'./InsideDirectory';// PascalCase import/filename, camelCase export// badimportCheckBoxfrom'./check_box';// PascalCase import/export, snake_case filenameimportforty_twofrom'./forty_two';// snake_case import/filename, camelCase exportimportinside_directoryfrom'./inside_directory';// snake_case import, camelCase exportimportindexfrom'./inside_directory/index';// requiring the index file explicitlyimportinsideDirectoryfrom'./insideDirectory/index';// requiring the index file explicitly// goodimportCheckBoxfrom'./CheckBox';// PascalCase export/import/filenameimportfortyTwofrom'./fortyTwo';// camelCase export/import/filenameimportinsideDirectoryfrom'./insideDirectory';// camelCase export/import/directory name/implicit "index"// ^ supports both insideDirectory.js and insideDirectory/index.js
23.7 当你 export-default 一个函数时,函数名用小驼峰,文件名需要和函数名一致。
functionmakeStyleGuide(){// ...}exportdefaultmakeStyleGuide;
23.8 当你 export 一个结构体/类/单例/函数库/对象 时用大驼峰。
constAirbnbStyleGuide={es6: {}};exportdefaultAirbnbStyleGuide;
23.9 简称和缩写应该全部大写或全部小写。
为什么?名字都是给人读的,不是为了去适应计算机算法。
// badimportSmsContainerfrom'./containers/SmsContainer';// badconstHttpRequests=[// ...];// goodimportSMSContainerfrom'./containers/SMSContainer';// goodconstHTTPRequests=[// ...];// also goodconsthttpRequests=[// ...];// bestimportTextMessageContainerfrom'./containers/TextMessageContainer';// bestconstrequests=[// ...];
23.10 你可以用全大写字母设置静态变量,他需要满足三个条件。
- 导出变量;
- 是
const定义的, 保证不能被改变; - 这个变量是可信的,他的子属性都是不能被改变的。
为什么?这是一个附加工具,帮助开发者去辨识一个变量是不是不可变的。UPPERCASE_VARIABLES 能让开发者知道他能确信这个变量(以及他的属性)是不会变的。
- 对于所有的
const变量呢? —— 这个是不必要的。大写变量不应该在同一个文件里定义并使用, 它只能用来作为导出变量。 - 那导出的对象呢? —— 大写变量处在
export的最高级(例如:EXPORTED_OBJECT.key) 并且他包含的所有子属性都是不可变的。(译者注:即导出的变量是全大写的,但他的属性不用大写)
// badconstPRIVATE_VARIABLE='should not be unnecessarily uppercased within a file';// badexportconstTHING_TO_BE_CHANGED='should obviously not be uppercased';// badexportletREASSIGNABLE_VARIABLE='do not use let with uppercase variables';// ---// 允许但不够语义化exportconstapiKey='SOMEKEY';// 在大多数情况下更好exportconstAPI_KEY='SOMEKEY';// ---// bad - 不必要的大写键,没有增加任何语义exportconstMAPPING={KEY: 'value'};// goodexportconstMAPPING={key: 'value'};
- 24.1 不需要使用属性的访问器函数。
24.2 不要使用 JavaScript 的 getters/setters,因为他们会产生副作用,并且难以测试、维护和理解。相反的,你可以用
getVal()和setVal('hello')去创造你自己的访问器函数。// badclassDragon{getage(){// ...}setage(value){// ...}}// goodclassDragon{getAge(){// ...}setAge(value){// ...}}
24.3 如果属性/方法是
boolean, 用isVal()或hasVal()。// badif(!dragon.age()){returnfalse;}// goodif(!dragon.hasAge()){returnfalse;}
24.4 用
get()和set()函数是可以的,但是要一起用。classJedi{constructor(options={}){constlightsaber=options.lightsaber||'blue';this.set('lightsaber',lightsaber);}set(key,val){this[key]=val;}get(key){returnthis[key];}}
25.1 当传递数据载荷给事件时(不论是 DOM 还是像 Backbone 这样有很多属性的事件)。这使得后续的贡献者(程序员)向这个事件添加更多的数据时不用去找或者更新每个处理器。例如:
// 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});
26.1 jQuery 对象用
$变量表示。// badconstsidebar=$('.sidebar');// goodconst$sidebar=$('.sidebar');// goodconst$sidebarBtn=$('.sidebar-btn');
26.2 缓存 jQuery 查找。
// badfunctionsetSidebar(){$('.sidebar').hide();// ...$('.sidebar').css({'background-color': 'pink'});}// goodfunctionsetSidebar(){const$sidebar=$('.sidebar');$sidebar.hide();// ...$sidebar.css({'background-color': 'pink'});}
26.4 用 jQuery 对象查询作用域的
find方法查询。// bad$('ul','.sidebar').hide();// bad$('.sidebar').find('ul').hide();// good$('.sidebar ul').hide();// good$('.sidebar > ul').hide();// good$sidebar.find('ul').hide();
- 28.1 这是收集到的各种ES6特性的链接
- 箭头函数——Arrow Functions
- 类——Classes
- 对象缩写——Object Shorthand
- 对象简写——Object Concise
- 对象计算属性——Object Computed Properties
- 模板字符串——Template Strings
- 解构赋值——Destructuring
- 默认参数——Default Parameters
- 剩余参数——Rest
- 数组拓展——Array Spreads
- Let and Const
- 幂操作符——Exponentiation Operator
- 迭代器和生成器——Iterators and Generators
- 模块——Modules
28.2 不要用 TC39 proposals, TC39 还没有到 stage 3。
为什么? 它还不是最终版, 他可能还有很多变化,或者被撤销。我们想要用的是 JavaScript, 提议还不是 JavaScript。
标准库中包含一些功能受损但是由于历史原因遗留的工具类
29.1 用
Number.isNaN代替全局的isNaN。 eslint:no-restricted-globals为什么?全局
isNaN强制把非数字转成数字, 然后对于任何强转后为NaN的变量都返回true如果你想用这个功能,就显式的用它。// badisNaN('1.2');// falseisNaN('1.2.3');// true// goodNumber.isNaN('1.2.3');// falseNumber.isNaN(Number('1.2.3'));// true
29.2 用
Number.isFinite代替isFinite. eslint:no-restricted-globalsWhy? 理由同上,会把一个非数字变量强转成数字,然后做判断。
// badisFinite('2e3');// true// goodNumber.isFinite('2e3');// falseNumber.isFinite(parseInt('2e3',10));// true
30.1Yup.
functionfoo(){returntrue;}
- 30.2No, but seriously:
- 无论用哪个测试框架,你都需要写测试。
- 尽量去写很多小而美的纯函数,减少突变的发生
- 小心 stub 和 mock —— 这会让你的测试变得脆弱。
- 在 Airbnb 首选
mocha。tape偶尔被用来测试一些小的、独立的模块。 - 100% 测试覆盖率是我们努力的目标,即便实际上很少达到。
- 每当你修了一个 bug,都要写一个回归测试。 一个 bug 修复了,没有回归测试,很可能以后会再次出问题。
- On Layout & Web Performance
- String vs Array Concat
- Try/Catch Cost In a Loop
- Bang Function
- jQuery Find vs Context, Selector
- innerHTML vs textContent for script text
- Long String Concatenation
- Are JavaScript functions like
map(),reduce(), andfilter()optimized for traversing arrays? - Loading...
Learning ES6
Read This
Tools
- Code Style Linters
- Neutrino Preset - @neutrinojs/airbnb
Other Style Guides
- Google JavaScript Style Guide
- Google JavaScript Style Guide (Old)
- jQuery Core Style Guidelines
- Principles of Writing Consistent, Idiomatic JavaScript
- StandardJS
Other Styles
- Naming this in nested functions - Christian Johansen
- Conditional Callbacks - Ross Allen
- Popular JavaScript Coding Conventions on GitHub - JeongHoon Byun
- Multiple var statements in JavaScript, not superfluous - Ben Alman
Further Reading
- Understanding JavaScript Closures - Angus Croll
- Basic JavaScript for the impatient programmer - Dr. Axel Rauschmayer
- You Might Not Need jQuery - Zack Bloom & Adam Schwartz
- ES6 Features - Luke Hoban
- Frontend Guidelines - Benjamin De Cock
Books
- JavaScript: The Good Parts - Douglas Crockford
- JavaScript Patterns - Stoyan Stefanov
- Pro JavaScript Design Patterns - Ross Harmes and Dustin Diaz
- High Performance Web Sites: Essential Knowledge for Front-End Engineers - Steve Souders
- Maintainable JavaScript - Nicholas C. Zakas
- JavaScript Web Applications - Alex MacCaw
- Pro JavaScript Techniques - John Resig
- Smashing Node.js: JavaScript Everywhere - Guillermo Rauch
- Secrets of the JavaScript Ninja - John Resig and Bear Bibeault
- Human JavaScript - Henrik Joreteg
- Superhero.js - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy
- JSBooks - Julien Bouquillon
- Third Party JavaScript - Ben Vinegar and Anton Kovalyov
- Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript - David Herman
- Eloquent JavaScript - Marijn Haverbeke
- You Don’t Know JS: ES6 & Beyond - Kyle Simpson
Blogs
- JavaScript Weekly
- JavaScript, JavaScript...
- Bocoup Weblog
- Adequately Good
- NCZOnline
- Perfection Kills
- Ben Alman
- Dmitry Baranovskiy
- nettuts
Podcasts
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
- 4Catalyzer: 4Catalyzer/javascript
- Aan Zee: AanZee/javascript
- Airbnb: airbnb/javascript
- AloPeyk: AloPeyk
- AltSchool: AltSchool/javascript
- Apartmint: apartmint/javascript
- Ascribe: ascribe/javascript
- Avant: avantcredit/javascript
- Axept: axept/javascript
- Billabong: billabong/javascript
- Bisk: bisk
- Bonhomme: bonhommeparis/javascript
- Brainshark: brainshark/javascript
- CaseNine: CaseNine/javascript
- Cerner: Cerner
- Chartboost: ChartBoost/javascript-style-guide
- Coeur d'Alene Tribe: www.cdatribe-nsn.gov
- ComparaOnline: comparaonline/javascript
- Compass Learning: compasslearning/javascript-style-guide
- DailyMotion: dailymotion/javascript
- DoSomething: DoSomething/eslint-config
- Digitpaintdigitpaint/javascript
- Drupal: www.drupal.org
- Ecosia: ecosia/javascript
- Evernote: evernote/javascript-style-guide
- Evolution Gaming: evolution-gaming/javascript
- EvozonJs: evozonjs/javascript
- ExactTarget: ExactTarget/javascript
- Flexberry: Flexberry/javascript-style-guide
- Gawker Media: gawkermedia
- General Electric: GeneralElectric/javascript
- Generation Tux: GenerationTux/javascript
- GoodData: gooddata/gdc-js-style
- GreenChef: greenchef/javascript
- Grooveshark: grooveshark/javascript
- Grupo-Abraxas: Grupo-Abraxas/javascript
- Happeo: happeo/javascript
- Honey: honeyscience/javascript
- How About We: howaboutwe/javascript
- HubSpot: HubSpot/javascript
- Hyper: hyperoslo/javascript-playbook
- InterCity Group: intercitygroup/javascript-style-guide
- Jam3: Jam3/Javascript-Code-Conventions
- JSSolutions: JSSolutions/javascript
- Kaplan Komputing: kaplankomputing/javascript
- KickorStick: kickorstick
- Kinetica Solutions: kinetica/javascript
- LEINWAND: LEINWAND/javascript
- Lonely Planet: lonelyplanet/javascript
- M2GEN: M2GEN/javascript
- Mighty Spring: mightyspring/javascript
- MinnPost: MinnPost/javascript
- MitocGroup: MitocGroup/javascript
- Muber: muber
- National Geographic Society: natgeosociety
- NullDev: NullDevCo/JavaScript-Styleguide
- Nulogy: nulogy/javascript
- Orange Hill Development: orangehill/javascript
- Orion Health: orionhealth/javascript
- Peerby: Peerby/javascript
- Pier 1: Pier1/javascript
- Qotto: Qotto/javascript-style-guide
- React: https://legacy.reactjs.org/docs/how-to-contribute.html#style-guide
- REI: reidev/js-style-guide
- Ripple: ripple/javascript-style-guide
- Sainsbury’s Supermarkets: jsainsburyplc
- Shutterfly: shutterfly/javascript
- Sourcetoad: sourcetoad/javascript
- Springload: springload
- StratoDem Analytics: stratodem/javascript
- SteelKiwi Development: steelkiwi/javascript
- StudentSphere: studentsphere/javascript
- SwoopApp: swoopapp/javascript
- SysGarage: sysgarage/javascript-style-guide
- Syzygy Warsaw: syzygypl/javascript
- Target: target/javascript
- Terra: terra
- TheLadders: TheLadders/javascript
- The Nerdery: thenerdery/javascript-standards
- Tomify: tomprats
- Traitify: traitify/eslint-config-traitify
- T4R Technology: T4R-Technology/javascript
- UrbanSim: urbansim
- VoxFeed: VoxFeed/javascript-style-guide
- WeBox Studio: weboxstudio/javascript
- Weggo: Weggo/javascript
- Zillow: zillow/javascript
- ZocDoc: ZocDoc/javascript
This style guide is also available in other languages:
Brazilian Portuguese: armoucar/javascript-style-guide
Bulgarian: borislavvv/javascript
Catalan: fpmweb/javascript-style-guide
Chinese (Simplified): lin-123/javascript
Chinese (Traditional): jigsawye/javascript
French: nmussy/javascript-style-guide
German: timofurrer/javascript-style-guide
Italian: sinkswim/javascript-style-guide
Japanese: mitsuruog/javascript-style-guide
Korean: ParkSB/javascript-style-guide
Russian: leonidlebedev/javascript-airbnb
Spanish: paolocarrasco/javascript-style-guide
Thai: lvarayut/javascript-style-guide
Turkish: eraycetinay/javascript
Ukrainian: ivanzusko/javascript
Vietnam: dangkyokhoang/javascript-style-guide
- Find us on gitter.
(The MIT License)
Copyright (c) 2012 Airbnb
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
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.