Rule
Don't use break in inner loops.
Break statements in deeply nested loops make
control flow hard to follow without clear documentation.
Supported languages: 45+Introduction
Break statements in nested loops create ambiguity about which loop exits and under what conditions. When a break appears deep inside multiple loops, readers must carefully trace back to determine which loop it terminates and whether outer loops continue executing. This cognitive overhead increases with each nesting level, making the code difficult to understand and maintain.
Why it matters
Code maintainability: Break statements in nested loops obscure control flow. Future maintainers must mentally track which loop breaks and what happens to outer loops. This becomes error-prone when modifying loop logic or adding new conditions.
Debugging complexity: When debugging nested loops with breaks, setting breakpoints and stepping through code requires understanding complex exit paths. A break in an inner loop might prevent important cleanup or validation logic in outer loops from executing.
Code examples
❌ Non-compliant:
function findUser(users, id) {
let found = null;
for (let i = 0; i < users.length; i++) {
if (users[i].id === id) {
found = users[i];
break; // break is okay, but this pattern is verbose
}
}
return found;
}Why it's wrong: The break statement requires introducing a temporary variable (found) to hold the result, then returning it after the loop. This verbose pattern adds unnecessary complexity and makes the code harder to follow compared to direct returns or array methods.
✅ Compliant:
function findUser(users, id) {
return users.find(user => user.id === id);
}
OR
function findUser(users, id) {
for (let i = 0; i < users.length; i++) {
if (users[i].id === id) {
return users[i];
}
}
return null;
}Why this matters: Option 1 uses .find() which is concise and clearly expresses intent. Option 2 uses return to exit immediately when the user is found, eliminating the need for temporary variables and break statements. Both approaches are clearer and more maintainable than the break pattern.
Conclusion
Extract nested loop logic into functions where return clearly exits all loops. Use array methods like find(), some(), or every() to replace inner loops when possible. If nested loops are unavoidable, use labeled breaks or flags to make exit conditions explicit.
.avif)
