25th-style 中文文档教程
25th-floor JavaScript Style Guide
一种最合理的 JavaScript 方法 基于令人惊叹的 AirBnB 风格指南。 谢谢你们!
其他风格指南
Table of Contents
- Types
- References
- Objects
- Arrays
- Destructuring
- Strings
- Functions
- Arrow Functions
- Constructors
- Modules
- Iterators and Generators
- Properties
- Variables
- Hoisting
- Comparison Operators & Equality
- Blocks
- Comments
- Whitespace
- Commas
- Semicolons
- Type Casting & Coercion
- Naming Conventions
- Accessors
- Events
- jQuery
- ECMAScript 5 Compatibility
- ECMAScript 6 Styles
- Testing
- Performance
- Resources
- In the Wild
- Translation
- The JavaScript Style Guide Guide
- Chat With Us About JavaScript
- Contributors
- License
Types
1.1 Primitives:当你访问一个 primitives键入您直接处理它的值。
string
number
boolean
null
undefined
const foo = 1; let bar = foo; bar = 9; console.log(foo, bar); // => 1, 9
1.2 复杂:当您访问复杂类型时,您会处理对其值的引用。
object
array
function
const foo = [1, 2]; const bar = foo; bar[0] = 9; console.log(foo[0], bar[0]); // => 9, 9
References
2.1 对所有引用使用
const
; 避免使用var
。 eslint:prefer-const
,no-const-assign
为什么? 这确保您不能重新分配您的引用,这可能会导致错误和难以理解的代码。
// bad var a = 1; var b = 2; // good const a = 1; const b = 2;
2.2 如果必须重新分配引用,请使用
let
而不是var
。 eslint:no-var
jscs:disallowVar
为什么?
let
是块范围的,而不是像var
那样的函数范围的。// bad var count = 1; if (true) { count += 1; } // good, use the let. let count = 1; if (true) { count += 1; }
2.3 注意
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 使用文字语法创建对象。 eslint:
no-new-object
// bad const item = new Object(); // good const item = {};
3.2 如果您的代码将在脚本上下文中的浏览器中执行,请不要使用 保留字作为键。 它不会在 IE8 中工作。 更多信息。 可以在 ES6 模块和服务器端代码中使用它们。 jscs:
disallowIdentifierNames
// bad const superman = { default: { clark: 'kent' }, private: true, }; // good const superman = { defaults: { clark: 'kent' }, hidden: true, };
3.3 使用易读的同义词代替保留字。 jscs:
disallowIdentifierNames
// bad const superman = { class: 'alien', }; // bad const superman = { klass: 'alien', }; // good const superman = { type: 'alien', };
3.4 在创建具有动态属性名称的对象时使用计算属性名称。
为什么? 它们允许您在一个地方定义一个对象的所有属性。
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.5 使用对象方法简写。 eslint:
object-shorthand
jscs:requireEnhancedObjectLiterals
// bad const atom = { value: 1,
}; // good const atom = { value: 1,addValue: function (value) { return atom.value + value; },
};addValue(value) { return atom.value + value; },
3.6 使用属性值简写。 eslint:
object-shorthand
jscs:requireEnhancedObjectLiterals
为什么? 书写和描述性较短。
const lukeSkywalker = 'Luke Skywalker'; // bad const obj = { lukeSkywalker: lukeSkywalker, }; // good const obj = { lukeSkywalker, };
3.7 在对象声明的开头对速记属性进行分组。
为什么? 更容易分辨哪些属性正在使用速记。
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.8 仅引用无效标识符的属性。 eslint:
quote-props
jscs:disallowQuotedKeysInObjects
为什么? 一般来说,我们认为它在主观上更容易阅读。 它改进了语法高亮,也更容易被许多 JS 引擎优化。
// bad
const bad = {
'foo': 3,
'bar': 4,
'data-blah': 5,
};
// good
const good = {
foo: 3,
bar: 4,
'data-blah': 5,
};
Arrays
4.1 使用文字语法创建数组。 eslint:
no-array-constructor
// bad const items = new Array(); // good const items = [];
4.2 使用 Array#push 而不是直接赋值来将项目添加到数组中。
const someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
4.3 使用数组展开
.. .
复制数组。// bad const len = items.length; const itemsCopy = []; let i; for (i = 0; i < len; i++) { itemsCopy[i] = items[i]; } // good const itemsCopy = [...items];
4.4 要将类数组对象转换为数组,请使用 Array#from。
const foo = document.querySelectorAll('.foo'); const nodes = Array.from(foo);
4.5 在数组方法回调中使用 return 语句。 如果函数体由 8.2 之后的单个语句组成,则可以省略 return。 eslint:
array-callback-return
// good [1, 2, 3].map((x) => { const y = x + 1; return x * y; }); // good [1, 2, 3].map(x => x + 1); // bad const flat = {}; [[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => { const flatten = memo.concat(item); flat[index] = memo.concat(item); }); // good const flat = {}; [[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => { const flatten = memo.concat(item); flat[index] = flatten; return flatten; }); // bad inbox.filter((msg) => { const { subject, author } = msg; if (subject === 'Mockingbird') { return author === 'Harper Lee'; } else { return false; } }); // good inbox.filter((msg) => { const { subject, author } = msg; if (subject === 'Mockingbird') { return author === 'Harper Lee'; }
});return false;
Destructuring
5.1 在以下情况下使用对象解构访问和使用对象的多个属性。 jscs:
requireObjectDestructuring
为什么? 解构使您免于为这些属性创建临时引用。
// bad function getFullName(user) { const firstName = user.firstName; const lastName = user.lastName;
} // good function getFullName(user) { const { firstName, lastName } = user; return `${firstName} ${lastName}`; } // best function getFullName({ firstName, lastName }) { return `${firstName} ${lastName}`; }return `${firstName} ${lastName}`;
5.2 使用数组解构。 jscs:
requireArrayDestructuring
const arr = [1, 2, 3, 4]; // bad const first = arr[0]; const second = arr[1]; // good const [first, second] = arr;
5.3 对多个返回值使用对象解构,而不是数组解构。
为什么? 您可以随着时间的推移添加新属性或更改事物的顺序而不会中断调用站点。
// 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, right } = processInput(input);
Strings
6.1 对字符串使用单引号
''
。 eslint:quotes
jscs:validateQuoteMarks
// bad const name = "Capt. Janeway"; // good const name = 'Capt. Janeway';
6.2 导致该行的字符串超过 120 个字符应使用字符串连接跨多行书写。
6.3 注意:如果过度使用,连接的长字符串可能会影响性能。 jsPerf & 讨论。
// 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.4 以编程方式构建字符串时,使用模板字符串而不是连接。 eslint:
prefer-template
template-curly-spacing
jscs:requireTemplateStrings
为什么? 模板字符串为您提供可读、简洁的语法以及适当的换行符和字符串插值功能。
// bad function sayHi(name) { return 'How are you, ' + name + '?'; } // bad function sayHi(name) { return ['How are you, ', name, '?'].join(); } // bad function sayHi(name) { return `How are you, ${ name }?`; } // good function sayHi(name) { return `How are you, ${name}?`; }
6.5 永远不要在字符串上使用
eval()
,它会打开太多漏洞。
Functions
7.1 使用函数声明而不是函数表达式。 jscs:
requireFunctionDeclarations
为什么? 函数声明被命名,因此它们更容易在调用堆栈中识别。 此外,提升了函数声明的整个主体,而仅提升了函数表达式的引用。 这条规则使得始终使用箭头函数代替函数表达式成为可能。
// bad const foo = function () { }; // good function foo() { }
7.2 立即调用函数表达式:eslint:
wrap-iife
jscs:requireParenthesesAroundIIFE
< /a>为什么? 一个立即调用的函数表达式是一个单一的单元——将它和它的调用括号一起包装在括号中,清楚地表达了这一点。 请注意,在一个到处都是模块的世界中,您几乎不需要 IIFE。
// immediately-invoked function expression (IIFE) (function () { console.log('Welcome to the Internet. Please follow me.'); }());
7.3 永远不要在非函数块(if、while 等)中声明函数。 而是将函数分配给变量。 浏览器将允许您这样做,但它们对它的解释都不同,这是个坏消息。 eslint:
no-loop-func
7.4 注意:ECMA-262 将
块
定义为语句列表。 函数声明不是语句。 阅读 ECMA-262 关于这个问题的说明。// bad if (currentUser) { function test() { console.log('Nope.'); } } // good let test; if (currentUser) { test = () => { console.log('Yup.'); }; }
7.5 永远不要将参数命名为
arguments
。 这将优先于赋予每个函数范围的arguments
对象。// bad function nope(name, options, arguments) { // ...stuff... } // good function yup(name, options, args) { // ...stuff... }
7.6 永远不要使用
参数
, 选择使用 rest 语法...
代替。prefer-rest-params
为什么?
...
明确说明您要提取哪些参数。 另外,其余参数是一个真正的数组,而不是像arguments
那样的 Array-like。// bad function concatenateAll() { const args = Array.prototype.slice.call(arguments); return args.join(''); } // good function concatenateAll(...args) { return args.join(''); }
7.7 使用默认参数语法而不是变异函数争论。
// really bad function handleThings(opts) { // No! We shouldn't mutate function arguments. // Double bad: if opts is falsy it'll be set to an object which may // be what you want but it can introduce subtle bugs. opts = opts || {}; // ... } // still bad function handleThings(opts) { if (opts === void 0) { opts = {}; } // ... } // good function handleThings(opts = {}) { // ... }
7.8 使用默认参数避免副作用。
为什么? 他们很难推理。
var b = 1; // bad function count(a = b++) { console.log(a); } count(); // 1 count(); // 2 count(3); // 3 count(); // 3
7.9 始终将默认参数放在最后。
// bad function handleThings(opts = {}, name) { // ... } // good function handleThings(name, opts = {}) { // ... }
7.10 切勿使用 Function 构造函数创建新函数。
为什么? 以这种方式创建一个函数会评估一个类似于 eval() 的字符串,这会打开漏洞。
// bad var add = new Function('a', 'b', 'return a + b'); // still bad var subtract = Function('a', 'b', 'return a - b');
7.11 函数签名中的空格。
为什么? 一致性很好,在添加或删除名称时不必添加或删除空格。
// bad const f = function(){}; const g = function (){}; const h = function() {}; // good const x = function () {}; const y = function a() {};
7.12 永远不要改变参数。 eslint:
no-param-reassign
为什么? 操作作为参数传入的对象可能会在原始调用者中产生不需要的变量副作用。
// bad function f1(obj) { obj.key = 1; }; // good function f2(obj) { const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1; };
7.13 永远不要重新分配参数。 eslint:
no-param-reassign
为什么? 重新分配参数可能会导致意外行为,尤其是在访问
arguments
对象时。 它还可能导致优化问题,尤其是在 V8 中。// bad function f1(a) { a = 1; } function f2(a) { if (!a) { a = 1; } } // good function f3(a) { const b = a || 1; } function f4(a = 1) { }
Arrow Functions
8.1 当您必须使用函数表达式时(如传递匿名函数时),请使用箭头函数表示法。 eslint:
prefer-arrow-callback
,arrow-spacing
jscs:requireArrowFunctions
为什么? 它创建一个在
this
上下文中执行的函数版本,这通常是您想要的,并且是一种更简洁的语法。为什么不? 如果您有一个相当复杂的函数,您可以将该逻辑移出到它自己的函数声明中。
// bad [1, 2, 3].map(function (x) { const y = x + 1; return x * y; }); // good [1, 2, 3].map(x => { const y = x + 1; return x * y; });
8.2 如果函数体由单个表达式组成,则省略大括号并使用隐式返回。 否则,保留大括号并使用
return
语句。 eslint:arrow-parens
,arrow-body-style
jscs:disallowParenthesesAroundArrowParam
,requireShorthandArrowFunctions
为什么? 语法糖。 当多个函数链接在一起时,它读起来很好。
为什么不? 如果您打算返回一个对象。
// good [1, 2, 3].map(number => `A string containing the ${number}.`); // bad [1, 2, 3].map(number => { const nextNumber = number + 1; `A string containing the ${nextNumber}.`; }); // good [1, 2, 3].map((number) => { const nextNumber = number + 1; return `A string containing the ${nextNumber}.`; });
8.3 如果表达式跨越多行,请将其括在括号中以提高可读性。
为什么? 它清楚地显示了函数的开始和结束位置。
// bad [1, 2, 3].map(number => 'As time went by, the string containing the ' + `${number} became much longer. So we needed to break it over multiple ` + 'lines.' ); // good [1, 2, 3].map(number => ( `As time went by, the string containing the ${number} became much ` + 'longer. So we needed to break it over multiple lines.' ));
8.4 如果您的函数采用单个参数,请省略括号。 始终在多个参数周围包含括号。 eslint:
arrow-parens
jscs:disallowParenthesesAroundArrowParam
为什么? 减少视觉混乱。
// bad [1, 2, 3].map((x) => x * x); // good [1, 2, 3].map(x => x * x); // good [1, 2, 3].map(number => ( `A long string with the ${number}. It’s so long that we’ve broken it ` + 'over multiple lines!' )); // bad [1, 2, 3].map((x) => { const y = x + 1; return x * y; }); // good [1, 2, 3].map(x => { const y = x + 1; return x * y; });
8.5 避免将箭头函数语法 (
=>
) 与比较运算符 (<=
,>=
)。 eslint:no-confusing-arrow
// bad const itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize; // bad const itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize; // good const itemHeight = item => { return item.height > 256 ? item.largeSize : item.smallSize; }
Constructors
9.1 始终使用
类。 避免直接操作
prototype
。为什么?
class
语法更简洁,更容易推理。// bad function Queue(contents = []) { this._queue = [...contents]; } Queue.prototype.pop = function () { const value = this._queue[0]; this._queue.splice(0, 1); return value; } // good class Queue { constructor(contents = []) { this._queue = [...contents]; } pop() { const value = this._queue[0]; this._queue.splice(0, 1); return value; } }
9.2 使用
extends
进行继承。为什么? 它是一种在不破坏
instanceof
的情况下继承原型功能的内置方法。// bad const inherits = require('inherits'); function PeekableQueue(contents) { Queue.apply(this, contents); } inherits(PeekableQueue, Queue); PeekableQueue.prototype.peek = function () { return this._queue[0]; } // good class PeekableQueue extends Queue { peek() { return this._queue[0]; } }
9.3 方法可以返回
this
以帮助进行方法链接。// bad Jedi.prototype.jump = function () { this.jumping = true; return true; }; Jedi.prototype.setHeight = function (height) { this.height = height; }; const luke = new Jedi(); luke.jump(); // => true luke.setHeight(20); // => undefined // good class Jedi { jump() { this.jumping = true; return this; }
} const luke = new Jedi(); luke.jump() .setHeight(20);setHeight(height) { this.height = height; return this; }
9.4 编写自定义的 toString() 方法是可以的,只要确保它能成功运行并且不会产生副作用即可。
class Jedi { constructor(options = {}) { this.name = options.name || 'no name'; }
}getName() { return this.name; } toString() { return `Jedi - ${this.getName()}`; }
9.5 如果没有指定,类有一个默认构造函数。 空构造函数或仅委托给父类的构造函数是不必要的。
no-useless-constructor
// bad class Jedi { constructor() {}
} // bad class Rey extends Jedi { constructor(...args) { super(...args); } } // good class Rey extends Jedi { constructor(...args) { super(...args); this.name = 'Rey'; } }getName() { return this.name; }
Modules
10.1 始终使用模块(
import
/export
) 在非标准模块系统上。 您始终可以转换为您喜欢的模块系统。为什么? 模块是未来,让我们现在就开始使用未来吧。
// bad const AirbnbStyleGuide = require('./AirbnbStyleGuide'); module.exports = AirbnbStyleGuide.es6; // ok import AirbnbStyleGuide from './AirbnbStyleGuide'; export default AirbnbStyleGuide.es6; // best import { es6 } from './AirbnbStyleGuide'; export default es6;
10.2 不要使用通配符导入。
为什么? 这可确保您有一个默认导出。
// bad import * as AirbnbStyleGuide from './AirbnbStyleGuide'; // good import AirbnbStyleGuide from './AirbnbStyleGuide';
10.3 并且不要直接从导入导出。
为什么? 尽管单行代码很简洁,但使用一种清晰的导入方式和一种清晰的导出方式可以使事情保持一致。
// bad // filename es6.js export { es6 as default } from './airbnbStyleGuide'; // good // filename es6.js import { es6 } from './AirbnbStyleGuide'; export default es6;
Iterators and Generators
11.1 不要使用迭代器。 更喜欢 JavaScript 的高阶函数,如
map()
和reduce()
,而不是像for-of
这样的循环。 eslint:no-iterator
为什么? 这强制执行了我们不变的规则。 处理返回值的纯函数比处理副作用更容易推理。
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;
11.2 现在不要使用生成器。
为什么? 它们不能很好地转换为 ES5。
Properties
12.1 访问属性时使用点符号。 eslint:
dot-notation
jscs:requireDotNotation
const luke = { jedi: true, age: 28, }; // bad const isJedi = luke['jedi']; // good const isJedi = luke.jedi;
12.2 使用下标使用变量访问属性时的符号
[]
。const luke = { jedi: true, age: 28, }; function getProp(prop) { return luke[prop]; } const isJedi = getProp('jedi');
Variables
13.1 始终使用
const
来声明变量。 不这样做会导致全局变量。 我们希望避免污染全局命名空间。 星球队长警告过我们这一点。// bad superPower = new SuperPower(); // good const superPower = new SuperPower();
13.2 每个变量使用一个
const
声明。 eslint:one-var
jscs:disallowMultipleVarDecl
为什么? 以这种方式添加新的变量声明更容易,而且您永远不必担心将
;
换成,
或引入仅标点符号的差异。// bad const items = getItems(), goSportsTeam = true, dragonball = 'z'; // bad // (compare to above, and try to spot the mistake) const items = getItems(), goSportsTeam = true; dragonball = 'z'; // good const items = getItems(); const goSportsTeam = true; const dragonball = 'z';
13.3 将所有的
const
分组,然后将所有的let
s。为什么? 这在稍后您可能需要根据先前分配的变量之一分配变量时很有用。
// 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 在需要的地方分配变量,但是要放在合理的地方。
为什么?
let
和const
是块作用域而不是函数作用域。// bad - unnecessary function call function checkName(hasName) { const name = getName();
} // good function checkName(hasName) { if (hasName === 'test') { return false; }if (hasName === 'test') { return false; } if (name === 'test') { this.setName(''); return false; } return name;
}const name = getName(); if (name === 'test') { this.setName(''); return false; } return name;
13.5 尽可能使用赋值运算符简写。 eslint:
operator-assignment
为什么? 这提高了可读性,使表达式的实际作用更加清晰,并在长对象属性链的情况下消除了重复的表达式。
// bad foo.bar.blubb = foo.bar.blubb + 1; // good foo.bar.blubb += 1;
Hoisting
14.1
var
声明被提升到它们作用域的顶部,它们的赋值没有。const
和let
声明被称为 时间死区 (TDZ)。 了解为什么 typeof 不再安全 很重要。// we know this wouldn't work (assuming there // is no notDefined global variable) function example() { console.log(notDefined); // => throws a ReferenceError } // creating a variable declaration after you // reference the variable will work due to // variable hoisting. Note: the assignment // value of `true` is not hoisted. function example() { console.log(declaredButNotAssigned); // => undefined var declaredButNotAssigned = true; } // the interpreter is hoisting the variable // declaration to the top of the scope, // which means our example could be rewritten as: function example() { let declaredButNotAssigned; console.log(declaredButNotAssigned); // => undefined declaredButNotAssigned = true; } // using const and let function example() { console.log(declaredButNotAssigned); // => throws a ReferenceError console.log(typeof declaredButNotAssigned); // => throws a ReferenceError const declaredButNotAssigned = true; }
14.2 匿名函数表达式会提升它们的变量名,但不会提升函数赋值。
function example() { console.log(anonymous); // => undefined
}anonymous(); // => TypeError anonymous is not a function var anonymous = function () { console.log('anonymous function expression'); };
14.3 命名函数表达式提升变量名,而不是函数名或函数体。
function example() { console.log(named); // => undefined
} // the same is true when the function name // is the same as the variable name. function example() { console.log(named); // => undefinednamed(); // => TypeError named is not a function superPower(); // => ReferenceError superPower is not defined var named = function superPower() { console.log('Flying'); };
}named(); // => TypeError named is not a function var named = function named() { console.log('named'); }
14.4 函数声明提升了它们的名称和函数体。
function example() { superPower(); // => Flying
}function superPower() { console.log('Flying'); }
有关详细信息,请参阅 JavaScript 作用域与提升 Ben Cherry 吊装。
Comparison Operators & Equality
15.1 在
==
和!=
上使用===
和!==
,比较除外使用null
(或undefined
)。 eslint:eqeqeq
// bad if (name == 'John') { // ...stuff... } // good if (name === 'John') { // ...stuff... } // good if (name == null) { // ...stuff... }
15.2
if
等条件语句使用ToBoolean
抽象方法强制计算它们的表达式,并始终遵循以下简单规则:- Objects evaluate to true
- Undefined evaluates to false
- Null evaluates to false
- Booleans evaluate to the value of the boolean
- Numbers evaluate to false if +0, -0, or NaN, otherwise true
- Strings evaluate to false if an empty string
''
, otherwise true
if ([0] && []) { // true // an array (even an empty one) is an object, objects will evaluate to true }
15.3 使用快捷方式。
// bad if (name !== '') { // ...stuff... } // good if (name) { // ...stuff... } // bad if (collection.length > 0) { // ...stuff... } // good if (collection.length) { // ...stuff... }
15.4 有关详细信息,请参阅 Truth Equality 和 JavaScript,作者 Angus Croll。
15.5 在
case
和default
子句中使用大括号创建块包含词法声明的(例如let
、const
、function
和class
)。
为什么? 词法声明在整个
switch
块中可见,但仅在分配时才初始化,这仅在达到其case
时发生。 当多个case
子句试图定义同一事物时,这会导致问题。
eslint 规则:no-case-declarations
。
```javascript
// bad
switch (foo) {
case 1:
let x = 1;
break;
case 2:
const y = 2;
break;
case 3:
function f() {}
break;
default:
class C {}
}
// good
switch (foo) {
case 1: {
let x = 1;
break;
}
case 2: {
const y = 2;
break;
}
case 3: {
function f() {}
break;
}
case 4:
bar();
break;
default: {
class C {}
}
}
```
15.6 三元组不应嵌套,通常是单行表达式。
eslint 规则:
no-nested-ternary
。// bad const foo = maybe1 > maybe2 ? "bar" : value1 > value2 ? "baz" : null; // better const maybeNull = value1 > value2 ? 'baz' : null; const foo = maybe1 > maybe2 ? 'bar' : maybeNull; // best const maybeNull = value1 > value2 ? 'baz' : null; const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
15.7 避免不必要的三元语句。
eslint 规则:
no-unneeded-ternary
。// bad const foo = a ? a : b; const bar = c ? true : false; const baz = c ? false : true; // good const foo = a || b; const bar = !!c; const baz = !c;
Blocks
16.1 在所有多行块中始终使用大括号。
// bad if (test) return false; // good if (test) return false; // good if (test) { return false; } // bad if (test) { doThis(); } else doThat(); // good if (test) { doThis(); } else { doThat(); } // bad function foo() { return false; } // good function bar() { return false; }
16.2 如果您使用带有
if
和else< 的多行代码块/code>, 把
else
和你的代码放在同一行if
块的右大括号。 eslint:brace-style
jscs:disallowNewlineBeforeBlockStatements
// bad if (test) { thing1(); thing2(); } else { thing3(); } // good if (test) { thing1(); thing2(); } else { thing3(); }
Comments
17.1 使用
/** ... */
进行多行注释。 包括描述,为所有参数和返回值指定类型和值。// bad // make() returns a new element // based on the passed in tag name // // @param {String} tag // @return {Element} element function make(tag) {
} // good /** * make() returns a new element * based on the passed in tag name * * @param {String} tag * @return {Element} element */ function make(tag) {// ...stuff... return element;
}// ...stuff... return element;
17.2 使用
//
进行单行注释。 将单行评论放在评论主题上方的换行符上。 在注释之前放一个空行,除非它在块的第一行。// bad const active = true; // is current tab // good // is current tab const active = true; // bad function getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this._type || 'no type';
} // good function getType() { console.log('fetching type...');return type;
} // also good function getType() { // set the default type to 'no type' const type = this._type || 'no type';// set the default type to 'no type' const type = this._type || 'no type'; return type;
}return type;
17.3 在您的评论前加上
FIXME
或TODO
可以帮助其他开发者快速了解您是在指出需要重新审视的问题,还是在建议需要实施的问题解决方案。 这些与常规评论不同,因为它们是可操作的。 这些操作是FIXME——需要解决这个问题
或TODO——需要实施
。17.4 使用
// FIXME: 注释问题。
class Calculator extends Abacus { constructor() { super();
}// FIXME: shouldn't use a global here total = 0; }
17.5 使用
// TODO:
注释问题的解决方案。class Calculator extends Abacus { constructor() { super();
}// TODO: total should be configurable by an options param this.total = 0; }
Whitespace
18.1 使用设置为 4 个空格的软制表符。 eslint:
缩进
jscs:validateIndentation
// bad function foo() { ∙∙const name; } // bad function bar() { ∙∙∙∙∙∙const name; } // good function baz() { ∙∙∙∙const name; }
18.2 在前导前放置 1 个空格支撑。 eslint:
space-before-blocks
jscs:requireSpaceBeforeBlockStatements
// bad function test(){ console.log('test'); } // good function test() { console.log('test'); } // bad dog.set('attr',{ age: '1 year', breed: 'Bernese Mountain Dog', }); // good dog.set('attr', { age: '1 year', breed: 'Bernese Mountain Dog', });
18.3 在控制语句(
if
、while
等)的左括号前放置 1 个空格。 在函数调用和声明中,参数列表和函数名之间不要有空格。 eslint:space-after-keywords
,space-before-keywords
jscs:requireSpaceAfterKeywords
// bad if(isJedi) { fight (); } // good if (isJedi) { fight(); } // bad function fight () { console.log ('Swooosh!'); } // good function fight() { console.log('Swooosh!'); }
18.4 用空格分隔运算符. eslint:
space-infix-ops
jscs:requireSpaceBeforeBinaryOperators
,requireSpaceAfterBinaryOperators< /code>
// bad const x=y+5; // good const x = y + 5;
18.5 以单个换行符结束文件。
// bad (function (global) { // ...stuff... })(this);
// bad (function (global) { // ...stuff... })(this);↵ ↵
// good (function (global) { // ...stuff... })(this);↵
18.6 在制作长方法链(超过 2 个方法链)时使用缩进。 使用前导点 强调该行是方法调用,而不是新语句。 eslint:
newline-per-chained-call
no-whitespace-before-property
dot-location
// bad $('#items').find('.selected').highlight().end().find('.open').updateCount(); // bad $('#items'). find('.selected'). highlight(). end(). find('.open'). updateCount(); // good $('#items') .find('.selected') .highlight() .end() .find('.open') .updateCount(); // bad const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true) .attr('width', (radius + margin) * 2).append('svg:g') .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') .call(tron.led); // good const leds = stage.selectAll('.led') .data(data) .enter().append('svg:svg') .classed('led', true) .attr('width', (radius + margin) * 2) .append('svg:g') .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') .call(tron.led); // good const leds = stage.selectAll('.led').data(data);
18.7 在块之后和下一个语句之前留一个空行。 jscs:
requirePaddingNewLinesAfterBlocks
// bad if (foo) { return bar; } return baz; // good if (foo) { return bar; } return baz; // bad const obj = { foo() { }, bar() { }, }; return obj; // good const obj = { foo() { },
}; return obj; // bad const arr = [ function foo() { }, function bar() { }, ]; return arr; // good const arr = [ function foo() { },bar() { },
]; return arr;function bar() { },
18.8 不要用空行填充你的块。 eslint:
padded-blocks
jscs:disallowPaddingNewlinesInBlocks
// bad function bar() {
} // also bad if (baz) {console.log(foo);
} else { console.log(foo); } // good function bar() { console.log(foo); } // good if (baz) { console.log(qux); } else { console.log(foo); }console.log(qux);
18.9 不要在括号内添加空格。 eslint:
space-in-parens
jscs:disallowSpacesInsideParentheses
// bad function bar( foo ) { return foo; } // good function bar(foo) { return foo; } // bad if ( foo ) { console.log(foo); } // good if (foo) { console.log(foo); }
18.10 / a> 不要在括号内添加空格。 eslint:
array-bracket-spacing
jscs:disallowSpacesInsideArrayBrackets
// bad const foo = [ 1, 2, 3 ]; console.log(foo[ 0 ]); // good const foo = [1, 2, 3]; console.log(foo[0]);
18.11 / a> 在花括号内添加空格。 eslint:
object-curly-spacing
jscs:disallowSpacesInsideObjectBrackets
// bad const foo = {clark: 'kent'}; // good const foo = { clark: 'kent' };
18.12 / a> 避免代码行超过 100 个字符(包括空格)。 eslint:
max-len
jscs:maximumLineLength
为什么? 这确保了可读性和可维护性。
// bad const foo = 'Whatever national crop flips the window. The cartoon reverts within the screw. Whatever wizard constrains a helpful ally. The counterpart ascends!'; // 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 = 'Whatever national crop flips the window. The cartoon reverts within the screw. ' + 'Whatever wizard constrains a helpful ally. The counterpart ascends!'; // good $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' }, }) .done(() => console.log('Congratulations!')) .fail(() => console.log('You have failed this city.'));
Commas
19.1 前导逗号:没有。 eslint:
comma-style
jscs:
requireCommaBeforeLineBreak
// 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', };
19.2 附加尾随逗号:是的。 eslint:
comma-dangle
jscs:requireTrailingComma
为什么? 这导致更清晰的 git 差异。 此外,像 Babel 这样的转译器将删除转译代码中的额外尾随逗号,这意味着您不必担心旧版浏览器中的尾随逗号问题 .
// bad - git diff without trailing comma const hero = { firstName: 'Florence', - lastName: 'Nightingale' + lastName: 'Nightingale', + inventorOf: ['coxcomb graph', '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', ];
Semicolons
20.1 是的。 eslint:
semi
jscs :requireSemicolons
// bad (function () { const name = 'Skywalker' return name })() // good (() => { const name = 'Skywalker'; return name; }()); // good (guards against the function becoming an argument when two files with IIFEs are concatenated) ;(() => { const name = 'Skywalker'; return name; }());
阅读更多。
Type Casting & Coercion
21.1 在语句的开头执行类型转换。
21.2 字符串:
// => this.reviewScore = 9; // bad const totalScore = this.reviewScore + ''; // good const totalScore = String(this.reviewScore);
21.3 数字:使用
Number
进行类型转换,使用parseInt
始终使用基数来解析字符串。 eslint:radix
const inputValue = '4'; // bad const val = new Number(inputValue); // bad const val = +inputValue; // bad const val = inputValue >> 0; // bad const val = parseInt(inputValue); // good const val = Number(inputValue); // good const val = parseInt(inputValue, 10);
21.4 如果出于某种原因你正在做一些疯狂的事情并且
parseInt
是你的瓶颈并且需要为 performance reasons,发表评论解释为什么以及你在做什么。// 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;
21.5 注意:使用移位操作时要小心。 数字表示为 64 位值,但移位操作始终返回 32 位整数(来源)。 对于大于 32 位的整数值,位移位可能会导致意外行为。 讨论。 最大的有符号 32 位 Int 是 2,147,483,647:
2147483647 >> 0 //=> 2147483647 2147483648 >> 0 //=> -2147483648 2147483649 >> 0 //=> -2147483647
21.6 布尔值:
const age = 0; // bad const hasAge = new Boolean(age); // good const hasAge = Boolean(age); // good const hasAge = !!age;
Naming Conventions
22.1 避免使用单字母名称。 用你的命名来描述。
// bad function q() { // ...stuff... } // good function query() { // ..stuff.. }
22.2 在命名对象、函数和实例时使用驼峰式命名。 eslint:
camelcase
jscs:requireCamelCaseOrUpperCaseIdentifiers
// bad const OBJEcttsssss = {}; const this_is_my_object = {}; function c() {} // good const thisIsMyObject = {}; function thisIsMyFunction() {}
22.3 在命名构造函数或类。 eslint:
new-cap
jscs:requireCapitalizedConstructors
// 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', });
22.4 使用一个命名私有属性时前导下划线
_
。 eslint:no-underscore-dangle
jscs:disallowDanglingUnderscores
// bad this.__firstName__ = 'Panda'; this.firstName_ = 'Panda'; // good this._firstName = 'Panda';
22.5 不要保存对
this
的引用。 使用箭头函数或 Function#bind。 jscs:disallowNodeTypes
// 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); }; }
22.6 如果您的文件导出单个类,您的文件名应该正好是该类的名称。
// file contents class CheckBox { // ... } export default CheckBox; // in some other file // bad import CheckBox from './checkBox'; // bad import CheckBox from './check_box'; // good import CheckBox from './CheckBox';
22.7 export-default 函数时使用 camelCase。 您的文件名应与您的函数名称相同。
function makeStyleGuide() { } export default makeStyleGuide;
22.8 导出单例/函数库/裸对象时使用 PascalCase。
const AirbnbStyleGuide = { es6: { } }; export default AirbnbStyleGuide;
Accessors
23.1 Accessor functions for properties are not required.
23.2 Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use getVal() and setVal('hello').
// bad dragon.age(); // good dragon.getAge(); // bad dragon.age(25); // good dragon.setAge(25);
23.3 If the property is a
boolean
, useisVal()
orhasVal()
.// bad if (!dragon.age()) { return false; } // good if (!dragon.hasAge()) { return false; }
23.4 It's okay to create get() and set() functions, but be consistent.
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
24.1 When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass 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:
// 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
25.1 Prefix jQuery object variables with a
$
. jscs:requireDollarBeforejQueryAssignment
// bad const sidebar = $('.sidebar'); // good const $sidebar = $('.sidebar'); // good const $sidebarBtn = $('.sidebar-btn');
25.2 Cache jQuery lookups.
// bad function setSidebar() { $('.sidebar').hide();
} // good function setSidebar() { const $sidebar = $('.sidebar'); $sidebar.hide();// ...stuff... $('.sidebar').css({ 'background-color': 'pink' });
}// ...stuff... $sidebar.css({ 'background-color': 'pink' });
25.3 For DOM queries use Cascading
$('.sidebar ul')
or parent > child$('.sidebar > ul')
. jsPerf25.4 Use
find
with scoped jQuery object queries.// 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
- 26.1 Refer to Kangax's ES5 compatibility table.
ECMAScript 6 Styles
- 27.1 This is a collection of links to the various ES6 features.
25th-floor JavaScript Style Guide
A mostly reasonable approach to JavaScript based on the amazing AirBnB style guide. Thanks guys!
Other Style Guides
Table of Contents
- Types
- References
- Objects
- Arrays
- Destructuring
- Strings
- Functions
- Arrow Functions
- Constructors
- Modules
- Iterators and Generators
- Properties
- Variables
- Hoisting
- Comparison Operators & Equality
- Blocks
- Comments
- Whitespace
- Commas
- Semicolons
- Type Casting & Coercion
- Naming Conventions
- Accessors
- Events
- jQuery
- ECMAScript 5 Compatibility
- ECMAScript 6 Styles
- Testing
- Performance
- Resources
- In the Wild
- Translation
- The JavaScript Style Guide Guide
- Chat With Us About JavaScript
- Contributors
- License
Types
1.1 Primitives: When you access a primitive type you work directly on its value.
string
number
boolean
null
undefined
const foo = 1; let bar = foo; bar = 9; console.log(foo, bar); // => 1, 9
1.2 Complex: When you access a complex type you work on a reference to its value.
object
array
function
const foo = [1, 2]; const bar = foo; bar[0] = 9; console.log(foo[0], bar[0]); // => 9, 9
References
2.1 Use
const
for all of your references; avoid usingvar
. eslint:prefer-const
,no-const-assign
Why? This ensures that you can't reassign your references, which can lead to bugs and difficult to comprehend code.
// bad var a = 1; var b = 2; // good const a = 1; const b = 2;
2.2 If you must reassign references, use
let
instead ofvar
. eslint:no-var
jscs:disallowVar
Why?
let
is block-scoped rather than function-scoped likevar
.// 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.// 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
// bad const item = new Object(); // good const item = {};
3.2 If your code will be executed in browsers in script context, don't use reserved words as keys. It won't work in IE8. More info. It’s OK to use them in ES6 modules and server-side code. jscs:
disallowIdentifierNames
// bad const superman = { default: { clark: 'kent' }, private: true, }; // good const superman = { defaults: { clark: 'kent' }, hidden: true, };
3.3 Use readable synonyms in place of reserved words. jscs:
disallowIdentifierNames
// bad const superman = { class: 'alien', }; // bad const superman = { klass: 'alien', }; // good const superman = { type: 'alien', };
3.4 Use computed property names when creating objects with dynamic property names.
Why? They allow you to define all the properties of an object in one place.
function getKey(k) { return `a key named ${k}`; } // bad const obj = { id: 5, name: 'San Francisco', }; obj[getKey('enabled')] = true; // good const obj = { id: 5, name: 'San Francisco', [getKey('enabled')]: true, };
3.5 Use object method shorthand. eslint:
object-shorthand
jscs:requireEnhancedObjectLiterals
// bad const atom = { value: 1,
}; // good const atom = { value: 1,addValue: function (value) { return atom.value + value; },
};addValue(value) { return atom.value + value; },
3.6 Use property value shorthand. eslint:
object-shorthand
jscs:requireEnhancedObjectLiterals
Why? It is shorter to write and descriptive.
const lukeSkywalker = 'Luke Skywalker'; // bad const obj = { lukeSkywalker: lukeSkywalker, }; // good const obj = { lukeSkywalker, };
3.7 Group your shorthand properties at the beginning of your object declaration.
Why? It's easier to tell which properties are using the shorthand.
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.8 Only quote properties that are invalid identifiers. eslint:
quote-props
jscs:disallowQuotedKeysInObjects
Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.
// bad
const bad = {
'foo': 3,
'bar': 4,
'data-blah': 5,
};
// good
const good = {
foo: 3,
bar: 4,
'data-blah': 5,
};
Arrays
4.1 Use the literal syntax for array creation. eslint:
no-array-constructor
// bad const items = new Array(); // good const items = [];
4.2 Use Array#push instead of direct assignment to add items to an array.
const someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
4.3 Use array spreads
...
to copy arrays.// bad const len = items.length; const itemsCopy = []; let i; for (i = 0; i < len; i++) { itemsCopy[i] = items[i]; } // good const itemsCopy = [...items];
4.4 To convert an array-like object to an array, use Array#from.
const foo = document.querySelectorAll('.foo'); const nodes = Array.from(foo);
4.5 Use return statements in array method callbacks. It's ok to omit the return if the function body consists of a single statement following 8.2. eslint:
array-callback-return
// good [1, 2, 3].map((x) => { const y = x + 1; return x * y; }); // good [1, 2, 3].map(x => x + 1); // bad const flat = {}; [[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => { const flatten = memo.concat(item); flat[index] = memo.concat(item); }); // good const flat = {}; [[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => { const flatten = memo.concat(item); flat[index] = flatten; return flatten; }); // bad inbox.filter((msg) => { const { subject, author } = msg; if (subject === 'Mockingbird') { return author === 'Harper Lee'; } else { return false; } }); // good inbox.filter((msg) => { const { subject, author } = msg; if (subject === 'Mockingbird') { return author === 'Harper Lee'; }
});return false;
Destructuring
5.1 Use object destructuring when accessing and using multiple properties of an object. jscs:
requireObjectDestructuring
Why? Destructuring saves you from creating temporary references for those properties.
// bad function getFullName(user) { const firstName = user.firstName; const lastName = user.lastName;
} // good function getFullName(user) { const { firstName, lastName } = user; return `${firstName} ${lastName}`; } // best function getFullName({ firstName, lastName }) { return `${firstName} ${lastName}`; }return `${firstName} ${lastName}`;
5.2 Use array destructuring. jscs:
requireArrayDestructuring
const arr = [1, 2, 3, 4]; // bad const first = arr[0]; const second = arr[1]; // good const [first, second] = arr;
5.3 Use object destructuring for multiple return values, not array destructuring.
Why? You can add new properties over time or change the order of things without breaking call sites.
// bad function processInput(input) { // then a miracle occurs return [left, right, top, bottom]; } // the caller needs to think about the order of return data const [left, __, top] = processInput(input); // good function processInput(input) { // then a miracle occurs return { left, right, top, bottom }; } // the caller selects only the data they need const { left, right } = processInput(input);
Strings
6.1 Use single quotes
''
for strings. eslint:quotes
jscs:validateQuoteMarks
// bad const name = "Capt. Janeway"; // good const name = 'Capt. Janeway';
6.2 Strings that cause the line to go over 120 characters should be written across multiple lines using string concatenation.
6.3 Note: If overused, long strings with concatenation could impact performance. jsPerf & Discussion.
// 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.4 When programmatically building up strings, use template strings instead of concatenation. eslint:
prefer-template
template-curly-spacing
jscs:requireTemplateStrings
Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.
// bad function sayHi(name) { return 'How are you, ' + name + '?'; } // bad function sayHi(name) { return ['How are you, ', name, '?'].join(); } // bad function sayHi(name) { return `How are you, ${ name }?`; } // good function sayHi(name) { return `How are you, ${name}?`; }
6.5 Never use
eval()
on a string, it opens too many vulnerabilities.
Functions
7.1 Use function declarations instead of function expressions. jscs:
requireFunctionDeclarations
Why? Function declarations are named, so they're easier to identify in call stacks. Also, the whole body of a function declaration is hoisted, whereas only the reference of a function expression is hoisted. This rule makes it possible to always use Arrow Functions in place of function expressions.
// bad const foo = function () { }; // good function foo() { }
7.2 Immediately invoked function expressions: eslint:
wrap-iife
jscs:requireParenthesesAroundIIFE
Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this. Note that in a world with modules everywhere, you almost never need an IIFE.
// immediately-invoked function expression (IIFE) (function () { console.log('Welcome to the Internet. Please follow me.'); }());
7.3 Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears. eslint:
no-loop-func
7.4 Note: ECMA-262 defines a
block
as a list of statements. A function declaration is not a statement. Read ECMA-262's note on this issue.// bad if (currentUser) { function test() { console.log('Nope.'); } } // good let test; if (currentUser) { test = () => { console.log('Yup.'); }; }
7.5 Never name a parameter
arguments
. This will take precedence over thearguments
object that is given to every function scope.// bad function nope(name, options, arguments) { // ...stuff... } // good function yup(name, options, args) { // ...stuff... }
7.6 Never use
arguments
, opt to use rest syntax...
instead.prefer-rest-params
Why?
...
is explicit about which arguments you want pulled. Plus rest arguments are a real Array and not Array-like likearguments
.// bad function concatenateAll() { const args = Array.prototype.slice.call(arguments); return args.join(''); } // good function concatenateAll(...args) { return args.join(''); }
7.7 Use default parameter syntax rather than mutating function arguments.
// really bad function handleThings(opts) { // No! We shouldn't mutate function arguments. // Double bad: if opts is falsy it'll be set to an object which may // be what you want but it can introduce subtle bugs. opts = opts || {}; // ... } // still bad function handleThings(opts) { if (opts === void 0) { opts = {}; } // ... } // good function handleThings(opts = {}) { // ... }
7.8 Avoid side effects with default parameters.
Why? They are confusing to reason about.
var b = 1; // bad function count(a = b++) { console.log(a); } count(); // 1 count(); // 2 count(3); // 3 count(); // 3
7.9 Always put default parameters last.
// bad function handleThings(opts = {}, name) { // ... } // good function handleThings(name, opts = {}) { // ... }
7.10 Never use the Function constructor to create a new function.
Why? Creating a function in this way evaluates a string similarly to eval(), which opens vulnerabilities.
// bad var add = new Function('a', 'b', 'return a + b'); // still bad var subtract = Function('a', 'b', 'return a - b');
7.11 Spacing in a function signature.
Why? Consistency is good, and you shouldn’t have to add or remove a space when adding or removing a name.
// bad const f = function(){}; const g = function (){}; const h = function() {}; // good const x = function () {}; const y = function a() {};
7.12 Never mutate parameters. eslint:
no-param-reassign
Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.
// bad function f1(obj) { obj.key = 1; }; // good function f2(obj) { const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1; };
7.13 Never reassign parameters. eslint:
no-param-reassign
Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the
arguments
object. It can also cause optimization issues, especially in V8.// bad function f1(a) { a = 1; } function f2(a) { if (!a) { a = 1; } } // good function f3(a) { const b = a || 1; } function f4(a = 1) { }
Arrow Functions
8.1 When you must use function expressions (as when passing an anonymous function), use arrow function notation. eslint:
prefer-arrow-callback
,arrow-spacing
jscs:requireArrowFunctions
Why? It creates a version of the function that executes in the context of
this
, which is usually what you want, and is a more concise syntax.Why not? If you have a fairly complicated function, you might move that logic out into its own function declaration.
// bad [1, 2, 3].map(function (x) { const y = x + 1; return x * y; }); // good [1, 2, 3].map(x => { const y = x + 1; return x * y; });
8.2 If the function body consists of a single expression, omit the braces and use the implicit return. Otherwise, keep the braces and use a
return
statement. eslint:arrow-parens
,arrow-body-style
jscs:disallowParenthesesAroundArrowParam
,requireShorthandArrowFunctions
Why? Syntactic sugar. It reads well when multiple functions are chained together.
Why not? If you plan on returning an object.
// good [1, 2, 3].map(number => `A string containing the ${number}.`); // bad [1, 2, 3].map(number => { const nextNumber = number + 1; `A string containing the ${nextNumber}.`; }); // good [1, 2, 3].map((number) => { const nextNumber = number + 1; return `A string containing the ${nextNumber}.`; });
8.3 In case the expression spans over multiple lines, wrap it in parentheses for better readability.
Why? It shows clearly where the function starts and ends.
// bad [1, 2, 3].map(number => 'As time went by, the string containing the ' + `${number} became much longer. So we needed to break it over multiple ` + 'lines.' ); // good [1, 2, 3].map(number => ( `As time went by, the string containing the ${number} became much ` + 'longer. So we needed to break it over multiple lines.' ));
8.4 If your function takes a single argument, omit the parentheses. Always include parentheses around multiple arguments. eslint:
arrow-parens
jscs:disallowParenthesesAroundArrowParam
Why? Less visual clutter.
// bad [1, 2, 3].map((x) => x * x); // good [1, 2, 3].map(x => x * x); // good [1, 2, 3].map(number => ( `A long string with the ${number}. It’s so long that we’ve broken it ` + 'over multiple lines!' )); // bad [1, 2, 3].map((x) => { const y = x + 1; return x * y; }); // good [1, 2, 3].map(x => { const y = x + 1; return x * y; });
8.5 Avoid confusing arrow function syntax (
=>
) with comparison operators (<=
,>=
). eslint:no-confusing-arrow
// bad const itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize; // bad const itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize; // good const itemHeight = item => { return item.height > 256 ? item.largeSize : item.smallSize; }
Constructors
9.1 Always use
class
. Avoid manipulatingprototype
directly.Why?
class
syntax is more concise and easier to reason about.// bad function Queue(contents = []) { this._queue = [...contents]; } Queue.prototype.pop = function () { const value = this._queue[0]; this._queue.splice(0, 1); return value; } // good class Queue { constructor(contents = []) { this._queue = [...contents]; } pop() { const value = this._queue[0]; this._queue.splice(0, 1); return value; } }
9.2 Use
extends
for inheritance.Why? It is a built-in way to inherit prototype functionality without breaking
instanceof
.// bad const inherits = require('inherits'); function PeekableQueue(contents) { Queue.apply(this, contents); } inherits(PeekableQueue, Queue); PeekableQueue.prototype.peek = function () { return this._queue[0]; } // good class PeekableQueue extends Queue { peek() { return this._queue[0]; } }
9.3 Methods can return
this
to help with method chaining.// bad Jedi.prototype.jump = function () { this.jumping = true; return true; }; Jedi.prototype.setHeight = function (height) { this.height = height; }; const luke = new Jedi(); luke.jump(); // => true luke.setHeight(20); // => undefined // good class Jedi { jump() { this.jumping = true; return this; }
} const luke = new Jedi(); luke.jump() .setHeight(20);setHeight(height) { this.height = height; return this; }
9.4 It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.
class Jedi { constructor(options = {}) { this.name = options.name || 'no name'; }
}getName() { return this.name; } toString() { return `Jedi - ${this.getName()}`; }
9.5 Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary.
no-useless-constructor
// bad class Jedi { constructor() {}
} // bad class Rey extends Jedi { constructor(...args) { super(...args); } } // good class Rey extends Jedi { constructor(...args) { super(...args); this.name = 'Rey'; } }getName() { return this.name; }
Modules
10.1 Always use modules (
import
/export
) over a non-standard module system. You can always transpile to your preferred module system.Why? Modules are the future, let's start using the future now.
// bad const AirbnbStyleGuide = require('./AirbnbStyleGuide'); module.exports = AirbnbStyleGuide.es6; // ok import AirbnbStyleGuide from './AirbnbStyleGuide'; export default AirbnbStyleGuide.es6; // best import { es6 } from './AirbnbStyleGuide'; export default es6;
10.2 Do not use wildcard imports.
Why? This makes sure you have a single default export.
// 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.
// bad // filename es6.js export { es6 as default } from './airbnbStyleGuide'; // good // filename es6.js import { es6 } from './AirbnbStyleGuide'; export default es6;
Iterators and Generators
11.1 Don't use iterators. Prefer JavaScript's higher-order functions like
map()
andreduce()
instead of loops likefor-of
. eslint:no-iterator
Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
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;
11.2 Don't use generators for now.
Why? They don't transpile well to ES5.
Properties
12.1 Use dot notation when accessing properties. eslint:
dot-notation
jscs:requireDotNotation
const luke = { jedi: true, age: 28, }; // bad const isJedi = luke['jedi']; // good const isJedi = luke.jedi;
12.2 Use subscript notation
[]
when accessing properties with a variable.const luke = { jedi: true, age: 28, }; function getProp(prop) { return luke[prop]; } const isJedi = getProp('jedi');
Variables
13.1 Always use
const
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.// bad superPower = new SuperPower(); // good const superPower = new SuperPower();
13.2 Use one
const
declaration per variable. eslint:one-var
jscs:disallowMultipleVarDecl
Why? It's easier to add new variable declarations this way, and you never have to worry about swapping out a
;
for a,
or introducing punctuation-only diffs.// 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.Why? This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
// bad let i, len, dragonball, items = getItems(), goSportsTeam = true; // bad let i; const items = getItems(); let dragonball; const goSportsTeam = true; let len; // good const goSportsTeam = true; const items = getItems(); let dragonball; let i; let length;
13.4 Assign variables where you need them, but place them in a reasonable place.
Why?
let
andconst
are block scoped and not function scoped.// bad - unnecessary function call function checkName(hasName) { const name = getName();
} // good function checkName(hasName) { if (hasName === 'test') { return false; }if (hasName === 'test') { return false; } if (name === 'test') { this.setName(''); return false; } return name;
}const name = getName(); if (name === 'test') { this.setName(''); return false; } return name;
13.5 Use assignment operator shorthands where possible. eslint:
operator-assignment
Why? This improves readability, makes it more clear what the expression actually does and eliminates repeated expressions in case of long object property chains.
// bad foo.bar.blubb = foo.bar.blubb + 1; // good foo.bar.blubb += 1;
Hoisting
14.1
var
declarations get hoisted to the top of their scope, their assignment does not.const
andlet
declarations are blessed with a new concept called Temporal Dead Zones (TDZ). It's important to know why typeof is no longer safe.// we know this wouldn't work (assuming there // is no notDefined global variable) function example() { console.log(notDefined); // => throws a ReferenceError } // creating a variable declaration after you // reference the variable will work due to // variable hoisting. Note: the assignment // value of `true` is not hoisted. function example() { console.log(declaredButNotAssigned); // => undefined var declaredButNotAssigned = true; } // the interpreter is hoisting the variable // declaration to the top of the scope, // which means our example could be rewritten as: function example() { let declaredButNotAssigned; console.log(declaredButNotAssigned); // => undefined declaredButNotAssigned = true; } // using const and let function example() { console.log(declaredButNotAssigned); // => throws a ReferenceError console.log(typeof declaredButNotAssigned); // => throws a ReferenceError const declaredButNotAssigned = true; }
14.2 Anonymous function expressions hoist their variable name, but not the function assignment.
function example() { console.log(anonymous); // => undefined
}anonymous(); // => TypeError anonymous is not a function var anonymous = function () { console.log('anonymous function expression'); };
14.3 Named function expressions hoist the variable name, not the function name or the function body.
function example() { console.log(named); // => undefined
} // the same is true when the function name // is the same as the variable name. function example() { console.log(named); // => undefinednamed(); // => TypeError named is not a function superPower(); // => ReferenceError superPower is not defined var named = function superPower() { console.log('Flying'); };
}named(); // => TypeError named is not a function var named = function named() { console.log('named'); }
14.4 Function declarations hoist their name and the function body.
function example() { superPower(); // => Flying
}function superPower() { console.log('Flying'); }
For more information refer to JavaScript Scoping & Hoisting by Ben Cherry.
Comparison Operators & Equality
15.1 Use
===
and!==
over==
and!=
, except for comparisons withnull
(orundefined
). eslint:eqeqeq
// bad if (name == 'John') { // ...stuff... } // good if (name === 'John') { // ...stuff... } // good if (name == null) { // ...stuff... }
15.2 Conditional statements such as the
if
statement evaluate their expression using coercion with theToBoolean
abstract method and always follow these simple rules:- Objects evaluate to true
- Undefined evaluates to false
- Null evaluates to false
- Booleans evaluate to the value of the boolean
- Numbers evaluate to false if +0, -0, or NaN, otherwise true
- Strings evaluate to false if an empty string
''
, otherwise true
if ([0] && []) { // true // an array (even an empty one) is an object, objects will evaluate to true }
15.3 Use shortcuts.
// bad if (name !== '') { // ...stuff... } // good if (name) { // ...stuff... } // bad if (collection.length > 0) { // ...stuff... } // good if (collection.length) { // ...stuff... }
15.4 For more information see Truth Equality and JavaScript by Angus Croll.
15.5 Use braces to create blocks in
case
anddefault
clauses that contain lexical declarations (e.g.let
,const
,function
, andclass
).
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.
eslint rules: no-case-declarations
.
```javascript
// bad
switch (foo) {
case 1:
let x = 1;
break;
case 2:
const y = 2;
break;
case 3:
function f() {}
break;
default:
class C {}
}
// good
switch (foo) {
case 1: {
let x = 1;
break;
}
case 2: {
const y = 2;
break;
}
case 3: {
function f() {}
break;
}
case 4:
bar();
break;
default: {
class C {}
}
}
```
15.6 Ternaries should not be nested and generally be single line expressions.
eslint rules:
no-nested-ternary
.// bad const foo = maybe1 > maybe2 ? "bar" : value1 > value2 ? "baz" : null; // better const maybeNull = value1 > value2 ? 'baz' : null; const foo = maybe1 > maybe2 ? 'bar' : maybeNull; // best const maybeNull = value1 > value2 ? 'baz' : null; const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
15.7 Avoid unneeded ternary statements.
eslint rules:
no-unneeded-ternary
.// bad const foo = a ? a : b; const bar = c ? true : false; const baz = c ? false : true; // good const foo = a || b; const bar = !!c; const baz = !c;
Blocks
16.1 Use braces consistently with all multi-line blocks.
// bad if (test) return false; // good if (test) return false; // good if (test) { return false; } // bad if (test) { doThis(); } else doThat(); // good if (test) { doThis(); } else { doThat(); } // 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
jscs:disallowNewlineBeforeBlockStatements
// bad if (test) { thing1(); thing2(); } else { thing3(); } // good if (test) { thing1(); thing2(); } else { thing3(); }
Comments
17.1 Use
/** ... */
for multi-line comments. Include a description, specify types and values for all parameters and return values.// bad // make() returns a new element // based on the passed in tag name // // @param {String} tag // @return {Element} element function make(tag) {
} // good /** * make() returns a new element * based on the passed in tag name * * @param {String} tag * @return {Element} element */ function make(tag) {// ...stuff... return element;
}// ...stuff... return element;
17.2 Use
//
for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it's on the first line of a block.// bad const active = true; // is current tab // good // is current tab const active = true; // bad function getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this._type || 'no type';
} // good function getType() { console.log('fetching type...');return type;
} // also good function getType() { // set the default type to 'no type' const type = this._type || 'no type';// set the default type to 'no type' const type = this._type || 'no type'; return type;
}return type;
17.3 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
.17.4 Use
// FIXME:
to annotate problems.class Calculator extends Abacus { constructor() { super();
}// FIXME: shouldn't use a global here total = 0; }
17.5 Use
// TODO:
to annotate solutions to problems.class Calculator extends Abacus { constructor() { super();
}// TODO: total should be configurable by an options param this.total = 0; }
Whitespace
18.1 Use soft tabs set to 4 spaces. eslint:
indent
jscs:validateIndentation
// bad function foo() { ∙∙const name; } // bad function bar() { ∙∙∙∙∙∙const name; } // good function baz() { ∙∙∙∙const name; }
18.2 Place 1 space before the leading brace. eslint:
space-before-blocks
jscs:requireSpaceBeforeBlockStatements
// bad function test(){ console.log('test'); } // good function test() { console.log('test'); } // bad dog.set('attr',{ age: '1 year', breed: 'Bernese Mountain Dog', }); // good dog.set('attr', { age: '1 year', breed: 'Bernese Mountain Dog', });
18.3 Place 1 space before the opening parenthesis in control statements (
if
,while
etc.). Place no space between the argument list and the function name in function calls and declarations. eslint:space-after-keywords
,space-before-keywords
jscs:requireSpaceAfterKeywords
// bad if(isJedi) { fight (); } // good if (isJedi) { fight(); } // bad function fight () { console.log ('Swooosh!'); } // good function fight() { console.log('Swooosh!'); }
18.4 Set off operators with spaces. eslint:
space-infix-ops
jscs:requireSpaceBeforeBinaryOperators
,requireSpaceAfterBinaryOperators
// bad const x=y+5; // good const x = y + 5;
18.5 End files with a single newline character.
// bad (function (global) { // ...stuff... })(this);
// bad (function (global) { // ...stuff... })(this);↵ ↵
// good (function (global) { // ...stuff... })(this);↵
18.6 Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which emphasizes that the line is a method call, not a new statement. eslint:
newline-per-chained-call
no-whitespace-before-property
dot-location
// bad $('#items').find('.selected').highlight().end().find('.open').updateCount(); // bad $('#items'). find('.selected'). highlight(). end(). find('.open'). updateCount(); // good $('#items') .find('.selected') .highlight() .end() .find('.open') .updateCount(); // bad const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true) .attr('width', (radius + margin) * 2).append('svg:g') .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') .call(tron.led); // good const leds = stage.selectAll('.led') .data(data) .enter().append('svg:svg') .classed('led', true) .attr('width', (radius + margin) * 2) .append('svg:g') .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') .call(tron.led); // good const leds = stage.selectAll('.led').data(data);
18.7 Leave a blank line after blocks and before the next statement. jscs:
requirePaddingNewLinesAfterBlocks
// bad if (foo) { return bar; } return baz; // good if (foo) { return bar; } return baz; // bad const obj = { foo() { }, bar() { }, }; return obj; // good const obj = { foo() { },
}; return obj; // bad const arr = [ function foo() { }, function bar() { }, ]; return arr; // good const arr = [ function foo() { },bar() { },
]; return arr;function bar() { },
18.8 Do not pad your blocks with blank lines. eslint:
padded-blocks
jscs:disallowPaddingNewlinesInBlocks
// bad function bar() {
} // also bad if (baz) {console.log(foo);
} else { console.log(foo); } // good function bar() { console.log(foo); } // good if (baz) { console.log(qux); } else { console.log(foo); }console.log(qux);
18.9 Do not add spaces inside parentheses. eslint:
space-in-parens
jscs:disallowSpacesInsideParentheses
// bad function bar( foo ) { return foo; } // good function bar(foo) { return foo; } // bad if ( foo ) { console.log(foo); } // good if (foo) { console.log(foo); }
18.10 Do not add spaces inside brackets. eslint:
array-bracket-spacing
jscs:disallowSpacesInsideArrayBrackets
// bad const foo = [ 1, 2, 3 ]; console.log(foo[ 0 ]); // good const foo = [1, 2, 3]; console.log(foo[0]);
18.11 Add spaces inside curly braces. eslint:
object-curly-spacing
jscs:disallowSpacesInsideObjectBrackets
// bad const foo = {clark: 'kent'}; // good const foo = { clark: 'kent' };
18.12 Avoid having lines of code that are longer than 100 characters (including whitespace). eslint:
max-len
jscs:maximumLineLength
Why? This ensures readability and maintainability.
// bad const foo = 'Whatever national crop flips the window. The cartoon reverts within the screw. Whatever wizard constrains a helpful ally. The counterpart ascends!'; // 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 = 'Whatever national crop flips the window. The cartoon reverts within the screw. ' + 'Whatever wizard constrains a helpful ally. The counterpart ascends!'; // good $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' }, }) .done(() => console.log('Congratulations!')) .fail(() => console.log('You have failed this city.'));
Commas
19.1 Leading commas: Nope. eslint:
comma-style
jscs:requireCommaBeforeLineBreak
// 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', };
19.2 Additional trailing comma: Yup. eslint:
comma-dangle
jscs:requireTrailingComma
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 in legacy browsers.
// bad - git diff without trailing comma const hero = { firstName: 'Florence', - lastName: 'Nightingale' + lastName: 'Nightingale', + inventorOf: ['coxcomb graph', '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', ];
Semicolons
20.1 Yup. eslint:
semi
jscs:requireSemicolons
// bad (function () { const name = 'Skywalker' return name })() // good (() => { const name = 'Skywalker'; return name; }()); // good (guards against the function becoming an argument when two files with IIFEs are concatenated) ;(() => { const name = 'Skywalker'; return name; }());
Type Casting & Coercion
21.1 Perform type coercion at the beginning of the statement.
21.2 Strings:
// => this.reviewScore = 9; // bad const totalScore = this.reviewScore + ''; // good const totalScore = String(this.reviewScore);
21.3 Numbers: Use
Number
for type casting andparseInt
always with a radix for parsing strings. eslint:radix
const inputValue = '4'; // bad const val = new Number(inputValue); // bad const val = +inputValue; // bad const val = inputValue >> 0; // bad const val = parseInt(inputValue); // good const val = Number(inputValue); // good const val = parseInt(inputValue, 10);
21.4 If for whatever reason you are doing something wild and
parseInt
is your bottleneck and need to use Bitshift for performance reasons, leave a comment explaining why and what you're doing.// 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;
21.5 Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values, but bitshift operations always return a 32-bit integer (source). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion. Largest signed 32-bit Int is 2,147,483,647:
2147483647 >> 0 //=> 2147483647 2147483648 >> 0 //=> -2147483648 2147483649 >> 0 //=> -2147483647
21.6 Booleans:
const age = 0; // bad const hasAge = new Boolean(age); // good const hasAge = Boolean(age); // good const hasAge = !!age;
Naming Conventions
22.1 Avoid single letter names. Be descriptive with your naming.
// bad function q() { // ...stuff... } // good function query() { // ..stuff.. }
22.2 Use camelCase when naming objects, functions, and instances. eslint:
camelcase
jscs:requireCamelCaseOrUpperCaseIdentifiers
// bad const OBJEcttsssss = {}; const this_is_my_object = {}; function c() {} // good const thisIsMyObject = {}; function thisIsMyFunction() {}
22.3 Use PascalCase when naming constructors or classes. eslint:
new-cap
jscs:requireCapitalizedConstructors
// 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', });
22.4 Use a leading underscore
_
when naming private properties. eslint:no-underscore-dangle
jscs:disallowDanglingUnderscores
// bad this.__firstName__ = 'Panda'; this.firstName_ = 'Panda'; // good this._firstName = 'Panda';
22.5 Don't save references to
this
. Use arrow functions or Function#bind. jscs:disallowNodeTypes
// 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); }; }
22.6 If your file exports a single class, your filename should be exactly the name of the class.
// file contents class CheckBox { // ... } export default CheckBox; // in some other file // bad import CheckBox from './checkBox'; // bad import CheckBox from './check_box'; // good import CheckBox from './CheckBox';
22.7 Use camelCase when you export-default a function. Your filename should be identical to your function's name.
function makeStyleGuide() { } export default makeStyleGuide;
22.8 Use PascalCase when you export a singleton / function library / bare object.
const AirbnbStyleGuide = { es6: { } }; export default AirbnbStyleGuide;
Accessors
23.1 Accessor functions for properties are not required.
23.2 Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use getVal() and setVal('hello').
// bad dragon.age(); // good dragon.getAge(); // bad dragon.age(25); // good dragon.setAge(25);
23.3 If the property is a
boolean
, useisVal()
orhasVal()
.// bad if (!dragon.age()) { return false; } // good if (!dragon.hasAge()) { return false; }
23.4 It's okay to create get() and set() functions, but be consistent.
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
24.1 When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass 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:
// 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
25.1 Prefix jQuery object variables with a
$
. jscs:requireDollarBeforejQueryAssignment
// bad const sidebar = $('.sidebar'); // good const $sidebar = $('.sidebar'); // good const $sidebarBtn = $('.sidebar-btn');
25.2 Cache jQuery lookups.
// bad function setSidebar() { $('.sidebar').hide();
} // good function setSidebar() { const $sidebar = $('.sidebar'); $sidebar.hide();// ...stuff... $('.sidebar').css({ 'background-color': 'pink' });
}// ...stuff... $sidebar.css({ 'background-color': 'pink' });
25.3 For DOM queries use Cascading
$('.sidebar ul')
or parent > child$('.sidebar > ul')
. jsPerf25.4 Use
find
with scoped jQuery object queries.// 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
- 26.1 Refer to Kangax's ES5 compatibility table.
ECMAScript 6 Styles
- 27.1 This is a collection of links to the various ES6 features.