Breaking Out of Nested Loops with Labels
You'll learn how to use labeled break statements to escape from deeply nested loops in one step, rather than breaking one level at a time.
The Problem with Deeply Nested Loops
When you have loops inside loops, a regular break statement only exits the innermost loop. If you need to escape from the outer loop immediately based on some condition deep inside, you'd normally have to use flags or awkward workarounds.
Labeled break provides a direct exit route.
How Labeled Break Works
You give the outer loop a label (like a name tag), then use break labelName from anywhere inside the nested structure to jump out completely:
outerLoop: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop; // exits BOTH loops immediately
}
console.log(`i: ${i}, j: ${j}`);
}
}
console.log("Done");
Output:
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
Done
Without the label, break would only exit the inner j loop, and the outer i loop would continue.
Think of It Like Fire Escapes
Imagine nested loops as floors in a building. A regular break takes the stairs down one floor. A labeled break is like a fire escape pole that drops you straight to ground level, bypassing all intermediate floors.
Key Takeaway: Use labeled break statements to exit outer loops directly from within nested structures, avoiding the need for flag variables or complex state tracking.