For-Loop Variable Not Used in Condition or Update
ID |
javascript.for_loop_var_not_used |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
control-flow, copy-paste, reliability |
Description
Reports a for loop whose initialiser declares one or more variables that are referenced in <em>neither</em> the condition nor the update expression:
for (let i = 0; n < 10; n++) { // i never used in cond/update
doStuff();
}
for (let row = 0; col < width; col++) { // wrong loop variable name
...
}
Rationale
Almost every loop of this shape is a copy-paste leftover or a half-finished rename: the developer started writing the header with one variable name and finished with another. The body may still terminate (via a break, an exception, …) but the visible loop relationship is broken — readers can no longer see, from the header alone, what makes the loop progress.
Remediation
Make the condition and the update reference the loop variable:
for (let i = 0; i < 10; i++) {
doStuff();
}
If the loop does not need a counter (for-of, for-in, while), use the matching construct:
for (const item of items) { ... }
while (cond) { ... }
Notes
The rule fires only when:
-
the initialiser declares at least one named variable (
var,let, orconst), -
the condition is non-empty,
-
the update is non-empty,
-
and none of the declared variables appears as an
Identifierin either the condition or the update.
Loops with no condition (for(;;)) or no update are explicit infinite-loop / break-from-body patterns and are not reported.