noForEach (since v12.1.0)
Prefer for...of
statement instead of Array.forEach
.
Here’s a summary of why forEach
may be disallowed, and why for...of
is preferred for almost any use-case of forEach
:
Performance: Using
forEach
can lead to performance issues, especially when working with large arrays. When more requirements are added on,forEach
typically gets chained with other methods likefilter
ormap
, causing multiple iterations over the same Array. Encouraging for loops discourages chaining and encourages single-iteration logic (e.g. using a continue instead offilter
).Readability: While
forEach
is a simple and concise way to iterate over an array, it can make the code less readable, especially when the callback function is complex. In contrast, using a for loop or afor...of
loop can make the code more explicit and easier to read.Debugging:
forEach
can make debugging more difficult, because it hides the iteration process.
Examples
Invalid
els.forEach(el => {
el
})
nursery/noForEach.js:1:1 lint/nursery/noForEach ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Prefer for...of instead of Array.forEach
> 1 │ els.forEach(el => {
│ ^^^^^^^^^^^^^^^^^^^
> 2 │ el
> 3 │ })
│ ^^
4 │
els['forEach'](el => {
el
})
nursery/noForEach.js:1:1 lint/nursery/noForEach ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Prefer for...of instead of Array.forEach
> 1 │ els['forEach'](el => {
│ ^^^^^^^^^^^^^^^^^^^^^^
> 2 │ el
> 3 │ })
│ ^^
4 │
Valid
for (const el of els) {
el
}