I was reading airbnb javascript guide. There is a particular statement, that says:
Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like for-in or for-of.
The reason they give for the above statement is:
This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
I could not differentiate between the two coding practices given:
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;
Could anyone explain, why should forEach
be preferred over regular for
loop? How does it really make a difference? Are there any side effects of using the regular iterators
?