New rule proposal: no-unreachable-loop
See original GitHub issuePlease describe what the rule should do:
Disallows loops which body exits the loop in all paths and therefore can never even reach the test condition for the second time (or first time if it’s do-while
), meaning that it isn’t actually a loop.
Targets while
, do-while
, for
, for-in
and for-of
loops.
What category of rule is this? (place an “X” next to just one item)
[X] Warns about a potential error (problem) [ ] 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:
while (foo) {
doSomething(foo);
foo = foo.parent;
break;
}
for (i = 0; i < arr.length; i++) {
if (isSomething(arr[i])) {
break;
} else {
return false;
}
}
do {
if (foo.type === "bar") {
return foo;
} else {
throw new Error("invalid");
}
} while (foo);
for (foo of bar) {
if (foo.type === "bar") {
doSomething(foo);
}
break;
}
for (foo in bar) break;
The code is correct only if the end of the body is reachable (i.e. loops from the end) or the loop has a continue
statement.
Why should this rule be included in ESLint (instead of a plugin)?
It’s a very possible error in the code, something is missing or something else is at the wrong place.
Even if it isn’t an error the code should be refactored to avoid unnecessary loop syntax.
This is a similar type of error as no-unreachable
, but I think this should be a separate rule because there is no particular unreachable code in these cases (except for the code in do-while
test and for-loop
update, but I think that no-unreachable
doesn’t report that).
In some cases both no-unreachable
and this rule can report warnings (e.g. no-unreachable
for code after the last break
, this rule for the whole loop), but I think that isn’t overlapping.
Are you willing to submit a pull request to implement this rule?
Yes, I’d love to work on this.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:3
- Comments:9 (9 by maintainers)
Top GitHub Comments
Any thoughts from the team about this rule? 😃
It looks to me that using the already existing code path analysis features this rule could reliably (without false negatives or false positives) detect these bugs in the code, and might be a nice complement to the
no-unreachable
rule.I’m working on this.