Unmodified Loop Condition
ID |
javascript.no_unmodified_loop |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
loops, reliability |
Description
Reports while and do-while loops whose condition references at least one identifier and whose body never modifies any of those identifiers and contains no function or method calls. The loop will execute its body forever (or never) because the condition has no chance to change.
Conservatively, the rule bails out when:
-
The condition has no identifier references at all (
while (true) {}is a deliberate idiom — out of scope). -
The body contains a
CallExpressionor a side-effecting unary (++,--,delete) — a call may mutate state we cannot track structurally. -
Any condition identifier resolves to a binding that is also written in the body.
for loops are out of scope: their separate update clause makes the analysis a different shape, and most simple for loops update a counter the rule wouldn’t usefully comment on.
Rationale
// Bad — `i` is never incremented; the loop spins forever or never runs.
function badWhile(items) {
let i = 0;
while (i < items.length) {
const value = items[i];
}
}
Remediation
Update the condition variable inside the body, or rewrite the loop using the form that pairs initialisation, condition and update in one place:
// Good
for (let i = 0; i < items.length; i++) {
const value = items[i];
}