Breaking Out of Nested Loops
Imagine a situation: you have a grid of numbers (a loop inside a loop), and upon finding the necessary element, you want to stop EVERYTHING. A regular break will only exit the inner loop, and the outer one will keep going.
Labels
A label is a name with a colon placed BEFORE a loop.
outerLoop: for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
if (found) break outerLoop; // Exit BOTH loops IMMEDIATELY
}
}
Important Rules
- A label does not allow you to jump to an arbitrary place in the code. It only works INSIDE the loop it's attached to.
- You can also use labels with
continue.
Important
The label name can be any legal variable name (top, main, here).
Warning
Don't confuse labels with the goto operator from other languages. JavaScript does not have goto; labels are used strictly for controlling loops.