Skip to content

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.

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);
}

This rule is not configurable.

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.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.