Course contentsShow
← JavaScript
Lesson 366 of 2,72310. LoopsFree lesson

Labeled statements: Targeting specific loops

Use labels to identify loops and reference them with break or continue to control outer loops from within nested ones.

Labeled Statements: Targeting Specific Loops

You'll learn how to use labels to break out of or continue outer loops when working with nested structures.

What Are Labeled Statements in Nested Loops?

You've learned that break and continue only affect the innermost loop they're inside. But what if you need to break out of an outer loop from deep within nested loops? That's where labels come in.

A label is a name you attach to a loop, letting you specifically target that loop with break or continue statements—even from inside nested loops.

The Syntax

outerLoop: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outerLoop; // Breaks the OUTER loop, not just inner
    }
    console.log(i, j);
  }
}
// Output: 0 0, 0 1, 0 2, 1 0
// Stops completely when i=1, j=1

Without the label, break would only exit the inner j loop. With outerLoop:, it exits both loops entirely.

Using Continue with Labels

searchRows: for (let row = 0; row < 3; row++) {
  for (let col = 0; col < 3; col++) {
    if (col === 1) {
      continue searchRows; // Skip to next row iteration
    }
    console.log(row, col);
  }
}
// Output: 0 0, 1 0, 2 0
// Only processes first column

The labeled continue jumps to the next iteration of the outer loop, skipping the rest of the inner loop.

Think of It Like This

Imagine nested loops as rooms inside buildings. A regular break only gets you out of the current room. A labeled break buildingExit gets you outside the entire building in one step.

Key Takeaway: Labels let you name loops and use break labelName or continue labelName to control outer loops from within nested structures, giving precise control over multi-level loop flow.