javascript / intermediate
Snippet
Breaking Out of Nested Loops with Labels
Labels allow you to identify a specific loop and break out of it from within a nested loop. This avoids using multiple flags or complex logic to exit deep nests.
snippet.js
javascript
1
2
3
4
5
6
outer: for (let i = 0; i < 3; i++) {for (let j = 0; j < 3; j++) {if (i === 1 && j === 1) break outer;console.log(`i:${i}, j:${j}`);}}
Breakdown
1
outer: for (...)
Assigns the name 'outer' to the top-level loop.
2
break outer;
Exits the outer loop entirely, not just the current inner one.