Skip to main content

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

javascript
labelName: { // statements }

Or, most often:

javascript
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

javascript
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:

javascript
i = 0, j = 0 i = 0, j = 1 i = 0, j = 2 i = 1, j = 0

Here break stops only the inner loop, and the outer one (i) continues.


Example with a label (label)

javascript
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:

javascript
i = 0, j = 0 i = 0, j = 1 i = 0, j = 2 i = 1, j = 0

Here 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:

javascript
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:

javascript
i = 0, j = 0 i = 0, j = 1 i = 1, j = 0 i = 1, j = 1 i = 2, j = 0 i = 2, j = 1

Important

  • Labels do not create new scopes: they are just names that break or continue can refer to.
  • You cannot use label for arbitrary jumps, like goto in 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 doesExample
Gives a name to a loop or a blockouter: for (...) { ... }
Lets you exit the outer loopbreak outer;
Lets you skip an iteration of the outer loopcontinue outer;
Does not create a new scopeYes
Use it often?No, only when needed

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.