Airbnb: Don’t use iterators like for-in
or for-of
When using airbnb, I noticed that for-in
and for-of
are restricted. This topic is to try to understand why and also try to find the best practice.
ESLint provides a rule: no-restricted-syntax. With this rule, Airbnb disallows certain syntax forms:
'no-restricted-syntax': [
'error',
{
selector: 'ForInStatement',
message: 'for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.',
},
{
selector: 'ForOfStatement',
message: 'iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.',
},
{
selector: 'LabeledStatement',
message: 'Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.',
},
{
selector: 'WithStatement',
message: '`with` is disallowed in strict mode because it makes code impossible to predict and optimize.',
},
],
I summarized all the loop/iterators related APIs here:
classic for loop
for...in
Array.prototype.forEach()
为 Array 对象引入了 Array.forEach 方法以代替 for 循环,Array.forEach 方法的特点是自带闭包,以解决因为缺乏块级作用域导致需要使用取巧的方法来解决 var 的作用域问题。Array.prototype.map()
Array.prototype.filter()
Array.prototype.reduce()
Array.prototype.every()
Array.prototype.some()
Object.keys()
for...of
ECMAScript 引入了一种新的循环语句 for...of,主要的用途是代替 for...in 循环语句, see difference.Array.prototype.keys()
Array.prototype.values()
Array.prototype.entries()
在 ES2015 标准中,数组类型再次被赋予了一个名为 entries 的方法,它可以返回对应的数组中每一个元素与其下标配对的一个新数组。Array.prototype.find()
Array.prototype.findIndex()
Array.from()
Array.prototype.includes()
indexOf 通过返回值是否等于-1 来获得查询对象是否被该数组包含。而 includes 则是通过返回 true 或者 false 来得出结果,对于只是查询是否包含,语义显得更清晰一些。
See TestLoop.js
"Best Choice"
I think Airbnb team do this for the following purpose:
- The polyfill of
for..of
doesn't work well and Airbnb still supports IE 11. They take it very seriously. - They encourage to use function in a "functional" way
Airbnb JavaScript Style Guide
Using 'ForOfStatement' is not allowed (no-restricted-syntax)
Array Iteration
Why and when to use forEach, map, filter, reduce, and find in JavaScript.