0
0
Javascriptprogramming~5 mins

Labeled break and continue in Javascript

Choose your learning style9 modes available
Introduction

Labeled break and continue help you control loops more precisely when you have nested loops. They let you jump out of or skip iterations in outer loops easily.

When you have loops inside loops and want to stop or skip the outer loop from inside the inner loop.
When searching for a value in a grid or table and want to stop all loops once found.
When processing nested lists and want to skip certain outer loop steps based on inner loop results.
When you want to avoid complex flags or extra variables to control multiple loops.
Syntax
Javascript
labelName: for (initialization; condition; increment) {
  // loop code
  if (condition) {
    break labelName; // exits the labeled loop
    // continue labelName; // skips to next iteration of labeled loop
  }
}

The label name is an identifier followed by a colon before the loop.

Use break labelName; to exit the labeled loop completely.

Use continue labelName; to skip to the next iteration of the labeled loop.

Examples
This breaks out of both loops when i and j are both 1.
Javascript
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outer;
    }
    console.log(i, j);
  }
}
This skips to the next iteration of the outer loop when j is 1, skipping inner loop steps.
Javascript
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) {
      continue outer;
    }
    console.log(i, j);
  }
}
Sample Program

This program multiplies i and j in nested loops. When the product is greater than 4, it breaks out of the outer loop completely.

Javascript
outerLoop: for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 3; j++) {
    if (i * j > 4) {
      break outerLoop;
    }
    console.log(`i=${i}, j=${j}, product=${i*j}`);
  }
}
OutputSuccess
Important Notes

Labels must be unique identifiers and placed before loops.

Using labeled break and continue can make code harder to read if overused, so use them only when simpler ways are not enough.

Summary

Labeled break and continue let you control outer loops from inside inner loops.

Use break label; to exit the labeled loop completely.

Use continue label; to skip to the next iteration of the labeled loop.