For Loop Update Direction Mismatch

ID

javascript.for_direction

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

JavaScript

Tags

reliability, suspicious-comparison

Description

Reports for loops whose update step counts in the opposite direction from the comparison: for (let i = 0; i < n; i--), for (let i = n - 1; i >= 0; i++), for (let i = 0; i < n; i -= 1). The result is either an infinite loop or a body that never runs — almost always a typo in the update or the comparison.

Rationale

  • for (let i = 0; i < n; i--) decrements i while the condition wants it to grow, so the loop never terminates.

  • for (let i = n - 1; i >= 0; i++) increments past n — the loop body still runs (potentially many extra times) but the original intent of "iterate downward" is broken.

  • The bug is invisible at small inputs (off-by-one quickly becomes infinite at scale) and notoriously hard to spot in code review.

// Bad
for (let i = 0; i < items.length; i--) {
  process(items[i]);  // never runs
}

for (let i = items.length - 1; i >= 0; i++) {
  process(items[i]);  // runs forever
}

Remediation

Match the update direction to the comparison.

// Good
for (let i = 0; i < items.length; i++) {
  process(items[i]);
}

for (let i = items.length - 1; i >= 0; i--) {
  process(items[i]);
}