noForEach
Diagnostic Category: lint/complexity/noForEach
Since: v1.0.0
Sources:
- Same as:
unicorn/no-array-for-each
- Same as:
needless_for_each
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.
Caveat
Section titled CaveatWe 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.
Exception for Index Usage
Section titled Exception for Index UsageWhen 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 offor...of
withObject.entries
that includes these entries. This can be important for certain array operations, particularly in TypeScript environments with strict type checking.
Examples
Section titled ExamplesInvalid
Section titled Invalidcode-block.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.
code-block.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.