Skip to content

helloint/test-array-loop

Repository files navigation

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

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.',
  },
],

Arrays built in methods

I summarized all the loop/iterators related APIs here:

ES5

ES6/ES2015

ES2016

  • Array.prototype.includes()
    indexOf 通过返回值是否等于-1 来获得查询对象是否被该数组包含。而 includes 则是通过返回 true 或者 false 来得出结果,对于只是查询是否包含,语义显得更清晰一些。

ES2017

Best Practice

See TestLoop.js "Best Choice"

My Understanding

I think Airbnb team do this for the following purpose:

  1. The polyfill of for..of doesn't work well and Airbnb still supports IE 11. They take it very seriously.
  2. They encourage to use function in a "functional" way

Related Topic

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.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published