skip to content

In JavaScript, how do a labelled break and a labelled continue behave inside nested loops, and what can a label not do?

level: middleimportance: nice to knowfreq 27%

answer

  1. an identifier prefixed to a statement
  2. plain break stops at the innermost
  3. ends versus next iteration
  4. no jump across a function
  5. not a goto

basics

~20 s

A labelled break ends the named statement and continues after it; a labelled continue starts the named loop's next iteration. A label is no goto: the jump must sit inside the labelled statement, in the same function.

solid answer

~50 s

A label is an identifier prefixed to a statement, such as `outer: for (...)`. A plain `break` exits only the innermost loop or `switch`, and a plain `continue` affects only the innermost loop. So `break outer` ends the outer loop too, while `continue outer` abandons the inner loop and starts the outer loop's next iteration. Without a label you need a boolean flag or an extracted function with `return`. The limits matter: the jump must be nested inside the statement carrying that label, and it cannot cross a function boundary, so `break outer` inside a `forEach` callback is a `SyntaxError`. `continue` needs a loop label, while `break` can also leave a labelled block. JavaScript has no `goto`, and these two statements are the only uses of a label. The label must also stay on the keyword's line, or semicolon insertion leaves a plain `break`.

code

javascript · 8 lines
javascript
const o = [];
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) continue outer;
    o.push(i * 10 + j);
  }
}
console.log(o); // [ 0, 1, 2, 10, 20, 21, 22 ]

go deeper

for a junior

Recall that a plain break exits only the innermost loop or switch, and that a label lets you name an outer loop. Be able to read a labelled loop even if you rarely write one.

for a middle

Predict the output of break label against continue label on a nested loop. State the limits: nested inside the labelled statement, no function boundary, and continue only for loops.

for a senior

Weigh a label against a flag or an extracted function by what the next reader sees. Spot the switch-in-a-loop case, where a plain break leaves the loop running, and the label on the next line that silently detaches.

for a principal

Labels rarely justify a standing rule of their own. Allow them where a helper would be worse, and let review judge readability, rather than spending a lint exception process on a rare construct.

## The problem labels solve A plain `break` exits only the innermost enclosing loop or `switch`, and a plain `continue` starts the next iteration of only the innermost loop. In a nested search that is often not enough, since finding a match in the inner loop should stop the outer one as well. A **label** names a statement, so `break` or `continue` can refer to it. The syntax is an identifier and a colon in front of a statement: ```javascript const grid = [[1, 2], [3, 4]]; let hit = null; search: for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { if (grid[i][j] === 3) { hit = [i, j]; break search; } } } console.log(hit); // [ 1, 0 ] ``` The name can be any identifier that is not a reserved word. ## break versus continue - **`break label`** terminates the labelled statement. Execution resumes at the statement immediately after it. - **`continue label`** abandons the current iteration of the labelled loop and continues with that loop's next iteration, including running its update expression. Tracing both over `i` and `j` from 0 to 2, with the jump at `i === 1 && j === 1` and `o.push(i * 10 + j)` after it: | Statement at the jump | `o` afterwards | Why | |---|---|---| | `break outer` | `[0, 1, 2, 10]` | The outer loop ends | | `continue outer` | `[0, 1, 2, 10, 20, 21, 22]` | Skips the rest of row 1 | | plain `continue` | `[0, 1, 2, 10, 12, 20, 21, 22]` | Skips one cell only | | plain `break` | `[0, 1, 2, 10, 20, 21, 22]` | Ends row 1 only | Note that `continue outer` and a plain `break` give the same output here. That holds only because the inner loop is the last thing in the outer loop's body. Add a statement after the inner loop and they differ: a plain `break` runs it, `continue outer` does not. ## What a label cannot do JavaScript has **no `goto`**, and these rules follow from that: 1. The `break` or `continue` must be **nested inside** the labelled statement. Referring to a label elsewhere is a `SyntaxError`. 2. A jump cannot **cross a function boundary**, even when the function is written inside the loop. `break outer` inside a `forEach` callback or an arrow function is a `SyntaxError`, since the callback's body is its own function. 3. `continue label` needs a **looping** statement. `continue foo` naming a labelled block is a `SyntaxError`. 4. Labels apply to statements, not declarations. A labelled generator or async function declaration is always a `SyntaxError`, and labelling a plain function is a deprecated form that strict mode rejects. These errors are raised when the code is parsed, so they appear before any line runs. ## Labelled blocks `break` can leave any labelled statement, not just a loop: - `foo: { a(); break foo; b(); }` runs `a` and skips `b`, then continues after the block. - It works as an early exit from a block of checks with no loop or function involved. - It is uncommon enough that many readers have to look it up, so an extracted function is often the kinder choice. ## Interaction with switch and semicolon insertion A `switch` inside a loop is the everyday reason for a label. A plain `break` in a clause exits only the `switch`, so the loop continues. `break outer`, naming the loop, ends both. A plain `continue` in a clause already reaches the loop, because `continue` ignores `switch`. `break` and `continue` are also **restricted productions**: a line terminator between the keyword and the label is forbidden, so a semicolon is inserted after the keyword. Inside nested loops, `break` with `outer` on the next line becomes a plain `break`, followed by an unreachable expression. It runs without any error and exits only the inner loop. Outside a loop or `switch`, the same layout is a `SyntaxError`, since a plain `break` is illegal there. ## When to use one Labels are legal and well defined, and the alternatives have their own costs: - A **flag** works everywhere but adds a variable and a check at each level. - An **extracted function with `return`** usually reads best, since the name documents the search and `return` leaves every loop at once. - A **label** suits a short, local nested loop where a helper would only move the code away, for example when it would need many local variables passed in. Many style guides discourage labels, so expect a reviewer to ask for the function form.

  • In JavaScript, what happens if `outer` is written on the line after `break`, inside nested loops?
    `break` is a restricted production, so a semicolon is inserted right after the keyword. The code becomes a plain `break;` followed by the expression `outer`, which never runs. No error appears and only the inner loop exits, so the outer loop keeps iterating. Outside any loop or `switch`, the same layout is a `SyntaxError`, because a plain `break` is illegal there.
  • How would you exit two nested JavaScript loops without using a label, and which form do you prefer?
    Either set a boolean flag that the outer loop checks after the inner loop, or move the loops into a function and `return` when done. I prefer the function: the name documents the search, and `return` leaves every level at once without extra state. A label stays reasonable for a short local loop where a helper would need many arguments.

  • A label lets you jump to any statement in the function, like goto.
  • Only loop statements can carry a label.
  • continue can target a labelled block as well as a loop.
  • break outer works from inside a forEach callback in that loop.
  • continue outer resumes the inner loop from where it stopped.
  • A plain break exits all of the loops around it.