Mike
Mike

Reputation: 203

eslint use for loop or forEach

There is eslint rule unicorn/no-array-for-each (link).

Use `for…of` instead of `Array#forEach(…)`            unicorn/no-array-for-each

Motivation for unicorn's rule is that it supports early return and is claimed to be faster. For an array like itemList = [{a:1},{a:2},{a:3}].

for (const item of itemList) {
    if (item.a > 1) break;
    console.log(item.a)
}

However, it would go into eslint error no-restricted-syntax (link).

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  no-restricted-syntax

It says for loop is heavyweight. It seems these two rules conflict with each other, which one makes more sense to be enabled?

Upvotes: 4

Views: 6886

Answers (1)

Mike
Mike

Reputation: 203

As @VLAX said, traditional for loop satisfies both rules.

for (let index = 0, l = itemList.length; index < l; index += 1) {
    const item = itemList[index];
    if (item.a > 1) break;
    console.log(item.a)  
}

Upvotes: 3

Related Questions