unicorn/no-array-for-each
Require a for...of loop instead of .forEach()
You can't leave a forEach early. break is a syntax error in the callback, and return only ends the current call. An await in the callback doesn't make the loop wait either. A for...of loop has break, continue, return, and await.
The rule can't tell what's an array. It reports every method call named forEach, including on a Map, a Set, or a NodeList. Those work with for...of too.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/no-array-for-each" = "error" # or "warn"Examples#
example.js1 problem
users.forEachDo not use Array#forEach((user) => {
if (!user.active) return;
notify(user);
});example.js1 problem
lines.forEachDo not use Array#forEach((line, index) => {
console.log(index + 1, line);
});example.jsNo problems
for (const user of users) {
if (!user.active) continue;
notify(user);
}Use .entries() when you need the index:
example.jsNo problems
for (const [index, line] of lines.entries()) {
console.log(index + 1, line);
}Children.forEach() and React.Children.forEach() aren't reported:
example.jsNo problems
React.Children.forEach(children, (child) => {
register(child);
});