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
breakorreturn - 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.
Examples
Section titled “Examples”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);});declare const array: number[];for (const element of array) { console.log(element);}declare const array: string[];for (const item of array) { process(item);}declare const array: number[];array.map((element) => element * 2);Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”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.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.