Skip to main content

no-unreachable-loop

A loop that can never reach its second iteration is usually a mistake. If you only need one iteration, use an if statement instead.
Rule Type: Problem
Fixable: No

Why This Rule Exists

Loops are meant to execute multiple times. If a loop always exits on the first iteration (via break, return, or throw), it should be refactored to use if statements instead.

Rule Details

This rule detects loops where all code paths exit the loop in the first iteration via:
  • break statement
  • return statement
  • throw statement
It checks these loop types:
  • while loops
  • do-while loops
  • for loops
  • for-in loops
  • for-of loops

Examples

Incorrect Code

Correct Code

Common Refactorings

Replace Loop with If Statement

Use Array Methods

Fix the Break Statement

Replace Break with Continue

Options

ignore

Type: Array<string> Specify loop types to ignore. Possible values:
  • "WhileStatement" - ignore while loops
  • "DoWhileStatement" - ignore do-while loops
  • "ForStatement" - ignore for loops
  • "ForInStatement" - ignore for-in loops
  • "ForOfStatement" - ignore for-of loops
Example: Sometimes you intentionally want to check only the first property:

Known Limitations

This rule uses static code path analysis and doesn’t evaluate conditions.
The rule may miss obvious cases:

When Not to Use It

This rule helps catch bugs, but you might disable it if:
  1. Your codebase uses loops for single-iteration patterns intentionally
  2. You’re using a framework that expects loop syntax for single operations
In most cases, refactoring to if statements will make code clearer.

Intentional Single Iteration

If you really need a loop that runs once: