forDirections
Reports for loops with counter variables that move in the wrong direction.
✅ This rule is included in the ts stylistic
preset.
A for loop with a counter that moves in the wrong direction relative to its stop condition will either run infinitely or never execute at all.
For example, if the counter is incrementing (using ++
or += positive
) but the condition expects the counter to be decreasing (like i >= 0
), the loop will never terminate.
While infinite loops are sometimes intentional, the convention is to use while
loops for such cases, making a wrong-direction for loop typically a bug.
Examples
Section titled “Examples”for (let i = 0; i < 10; i--) { console.log(i);}
for (let i = 10; i >= 0; i++) { console.log(i);}
for (let i = 0; i < 10; i -= 1) { process(i);}
const step = -2;for (let i = 0; i < 10; i += step) { handle(i);}
for (let i = 0; i < 10; i++) { console.log(i);}
for (let i = 10; i >= 0; i--) { console.log(i);}
for (let i = 0; i < 10; i += 1) { process(i);}
for (let i = 10; i > 0; i -= 1) { handle(i);}
Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If your project uses control flow structures that create confusing side effects, such as dynamic getters that modify state, you might not be able to enable this rule. Consider refactoring to more predictable control flow structures.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- Biome:
useValidForDirection
- Deno:
for-direction
- ESLint:
for-direction
- Oxlint:
eslint/for-direction