Skip to content

noForEach (since v1.0.0)

Diagnostic Category: lint/complexity/noForEach

Sources:

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 like filter or map, causing multiple iterations over the same Array. Encouraging for loops discourages chaining and encourages single-iteration logic (e.g. using a continue instead of filter).

  • 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 a for...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.

We consider all objects with a method named forEach to be iterable. This way, this rule applies to all objects with a method called forEach, not just Array instances.

When the index is explicitly used in the forEach callback, it is acceptable to use forEach. This is because:

  • The index is directly available as the second argument in forEach, making it convenient for scenarios where the index is necessary.
  • In sparse arrays, forEach will skip undefined entries, which differs from the behavior of for...of with Object.entries that includes these entries. This can be important for certain array operations, particularly in TypeScript environments with strict type checking.
els.forEach((el) => {
f(el);
})
complexity/noForEach.js:1:1 lint/complexity/noForEach ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

   Prefer for...of instead of forEach.
  
  > 1 │ els.forEach((el) => {
   ^^^^^^^^^^^^^^^^^^^^^
  > 2 │   f(el);
  > 3 │ })
   ^^
    4 │ 
  
   forEach may lead to performance issues when working with large arrays. When combined with functions like filter or map, this causes multiple iterations over the same type.
  
els["forEach"](el => {
f(el);
})
complexity/noForEach.js:1:1 lint/complexity/noForEach ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

   Prefer for...of instead of forEach.
  
  > 1 │ els["forEach"](el => {
   ^^^^^^^^^^^^^^^^^^^^^^
  > 2 │   f(el);
  > 3 │ })
   ^^
    4 │ 
  
   forEach may lead to performance issues when working with large arrays. When combined with functions like filter or map, this causes multiple iterations over the same type.
  
els.forEach((el, i) => {
f(el, i)
})
for (const el of els) {
f(el);
}