Loop Body Never Iterates

ID

javascript.no_unreachable_loop

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

JavaScript

Tags

dead-code, loops, reliability

Description

Reports loops whose body unconditionally exits on the first iteration. A for, while, do-while, for-in or for-of loop whose body’s first statement is always a return, throw or unlabeled break runs its body at most once — the loop construct adds no value over a single straight-line block.

The check is structural: only the body’s first statement (or the first statement of the body’s BlockStatement wrapper) is inspected. continue is excluded because it merely moves to the next iteration; the loop still progresses normally.

Rationale

// Bad — `for` runs at most once; the loop is just a roundabout `if`.
function first(items) {
  for (const x of items) {
    return x;
  }
  return null;
}

// Bad — same idea, with `throw`.
function alwaysThrows(items) {
  while (items.length) {
    throw new Error("nope");
  }
}

// Bad — `break` exits the loop on the first iteration.
function breakImmediately(items) {
  for (let i = 0; i < items.length; i++) {
    break;
  }
}

Remediation

Either drop the loop entirely (when the intent was to act on the single first item) or restructure so the body genuinely iterates:

// Good — direct access to the first item.
function first(items) {
  return items.length ? items[0] : null;
}

// Good — actually iterates and processes each item.
function process(items) {
  for (const x of items) {
    if (x > 100) return x;
    handle(x);
  }
}

References