Breaking to a Label: Exiting Multiple Levels
You'll learn how to use break with a label to jump out of multiple nested loops at once, landing exactly where you need to be.
The Problem with Nested Loops
When you have loops inside loops, a plain break statement only exits the innermost loop. But sometimes you need to escape all the loops at once — like finding a specific item in a 2D grid and stopping the entire search immediately.
How Labeled Break Works
By placing a label before an outer loop and using break labelName, you can exit directly from any level of nesting and jump to the statement right after the labeled loop:
outerLoop: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(`i: ${i}, j: ${j}`);
if (i === 1 && j === 1) {
break outerLoop; // Exits BOTH loops
}
}
}
console.log("Done!");
// Output:
// i: 0, j: 0
// i: 0, j: 1
// i: 0, j: 2
// i: 1, j: 0
// i: 1, j: 1
// Done!
Without the label, break would only exit the inner j loop, and the outer i loop would continue. With break outerLoop, execution jumps straight to the "Done!" line.
Real-World Example: Searching a Grid
searchGrid: for (let row = 0; row < 5; row++) {
for (let col = 0; col < 5; col++) {
if (row === 2 && col === 3) {
console.log("Found at row 2, col 3!");
break searchGrid; // Stop entire search
}
}
}
console.log("Search complete");
Key Takeaway: Use break with a label to exit multiple nested loops in one jump, making complex early-exit logic cleaner and more direct.