Linter · Rules
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
Reported:
users.forEach((user) => {
if (!user.active) return;
notify(user);
});
lines.forEach((line, index) => {
console.log(index + 1, line);
});
Not reported:
for (const user of users) {
if (!user.active) continue;
notify(user);
}
Use .entries() when you need the index:
for (const [index, line] of lines.entries()) {
console.log(index + 1, line);
}
Children.forEach() and React.Children.forEach() aren't reported:
React.Children.forEach(children, (child) => {
register(child);
});