Error no-restricted-syntax iterators / generator on Eslint Airbnb

0

I'm testing Eslint using the Airbn style guides, I use the airbnb-base package My doubt arises from this error in a loop for..of

error: no-restricted-syntax - iterator/generator

In the documentation says:

  

Do not use iterators. Prefer JavaScript's higher-order functions instead of loops like for-in or for-of.

and this is why:

  

Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.

Could you explain me with an example, how do you find the mutation that you mention using another type of iterator?

    
asked by Sebastian Gutierrez 06.04.2018 в 22:32
source

1 answer

0

I'll give you the airbnb explanation, whose style guide you're using. I suppose you will know that you can negate some of the rules, putting the first parameter in 'off', instead of in 'error' or 'warn'. Or you could even look at the Airbnb github, see what standards you are interested in and include only those ones one by one, so that you control what style you want to impose.

const numbers = [1, 2, 3, 4, 5];

// bad
let sum = 0;
for (let num of numbers) {
  sum += num;
}
sum === 15;

// good
let sum = 0;
numbers.forEach((num) => {
  sum += num;
});
sum === 15;

// best (use the functional force)
const sum = numbers.reduce((total, num) => total + num, 0);
sum === 15;

// bad
const increasedByOne = [];
for (let i = 0; i < numbers.length; i++) {
  increasedByOne.push(numbers[i] + 1);
}

// good
const increasedByOne = [];
numbers.forEach((num) => {
  increasedByOne.push(num + 1);
});

// best (keeping it functional)
const increasedByOne = numbers.map(num => num + 1);
    
answered by 17.04.2018 / 16:28
source