The label operator
The label operator (or a label) is a rare and rarely used tool in JavaScript that lets you give a name to a block of code or a loop, and then control execution with break or continue, specifying exactly which loop to stop or continue.
Syntax
labelName: {
// statements
}Or, most often:
labelName:
for (let i = 0; i < 5; i++) {
...
}Why label is needed
It is usually used when there are nested loops, and you need to exit not just the inner one but also the outer loop at once.
Without labels, break and continue only affect the nearest loop.
Example without a label
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) break;
console.log(`i = ${i}, j = ${j}`);
}
}Result:
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0Here break stops only the inner loop, and the outer one (i) continues.
Example with a label (label)
outerLoop: // a label for the outer loop
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) break outerLoop;
console.log(`i = ${i}, j = ${j}`);
}
}Result:
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0Here break outerLoop stops the entire outer loop, not just the inner one.
Example with continue and a label
You can also skip an iteration of the outer loop when a condition is met:
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 2) continue outer; // skips the current i
console.log(`i = ${i}, j = ${j}`);
}
}Result:
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1Important
- Labels do not create new scopes: they are just names that
breakorcontinuecan refer to. - You cannot use
labelfor arbitrary jumps, likegotoin other languages (for example, C). - Code with labels is often considered less readable, and they are used extremely rarely: only when there is no elegant way to exit nested loops without them.
The short way to remember it
| What it does | Example |
|---|---|
| Gives a name to a loop or a block | outer: for (...) { ... } |
| Lets you exit the outer loop | break outer; |
| Lets you skip an iteration of the outer loop | continue outer; |
| Does not create a new scope | Yes |
| Use it often? | No, only when needed |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.