`prefer-for-of` should include some Array methods (forEach, reduce)
See original GitHub issuePlease describe what the rule should do:
Rewriting forEach
and reduce
loops to for-of
increases their readability.
forEach
isn’t beneficial to anything unless you’re really into fp and one-liners.makes you create a single-use function when you might not need one, especially when nesting it.reduce
tends to create backwards logic, where the starting value of the loop is placed at the end. Example thread: https://twitter.com/jaffathecake/status/1213077702300852224
Other methods like map
and some
on the other hand are very effective and readable, so they should be left alone.
Prior art:
- https://github.com/mysticatea/eslint-plugin/blob/master/docs/rules/prefer-for-of.md
- https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/prefer-for-of.md
What category of rule is this? (place an “X” next to just one item)
[ ] Warns about a potential error (problem) [x] Suggests an alternate way of doing something (suggestion) [ ] Enforces code style (layout) [ ] Other (please specify:)
Provide 2-3 code examples that this rule will warn about:
👎 Examples of incorrect code for this rule:
[1, 2, 3].forEach(item => {
console.log(item);
});
const accumulator = [1, 2, 3].reduce((accumulator, item) => {
accumulator += item;
return accumulator;
}, 0);
👍 Examples of correct code for this rule:
for (const item of [1, 2, 3]) {
console.log(item);
}
let accumulator = 0;
for (const item of [1, 2, 3]) {
accumulator += item;
}
// async functions are allowed
[1, 2, 3].forEach(async item => {
throw new Error(item);
});
Why should this rule be included in ESLint (instead of a plugin)?
You already have prefer-for-of
in typescript-eslint
(which shouldn’t be there in the first place given it’s about a very basic feature of the language and unrelated to types)
Issue Analytics
- State:
- Created 4 years ago
- Reactions:4
- Comments:20 (16 by maintainers)
Top GitHub Comments
Then, just to confirm, this is a proposal for a new ESLint core rule which would disallow
.forEach()
,.reduce()
andfor
loop when any of these can be replaced with afor-of
loop?Sure. Just saying there are a lot of reasons why one might not want this rule.