Skip to content

arrayLoops

Reports using .forEach() when a for-of loop can be used.

✅ This rule is included in the ts stylistic presets.

for...of loops offer several benefits over the .forEach() method:

  • Ability to exit early with break or return
  • Ability to skip iterations with continue
  • TypeScript type narrowing works properly since no function boundary is crossed
  • Often better performance

This rule reports when .forEach() is called on arrays.

declare const array: number[];
array.forEach((element) => {
console.log(element);
});
declare const array: string[];
array.forEach(function (item) {
process(item);
});
[1, 2, 3].forEach((value) => {
handle(value);
});

This rule is not configurable.

If you prefer the functional style of .forEach(), or if your codebase uses it extensively for consistency, you may disable this rule. Note that this rule intentionally does not flag .forEach() on Set or Map since those cannot be as naturally replaced with for-of in all cases.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.