Back to all posts

Labeled statement


A labeled statement in JavaScript is a statement that is prefixed with a label name. This label name can then be used with the break and continue statement to control the flow of execution of the program.

The syntax for a labeled statement is as follows:

labelName: statement;

where labelName is the name if the label and statement is any valid JavaScript statement.

Here’s an example that demonstrates the usage of a labeled statement with a for loop:

outerLoop: for (var i = 0; i < 3; i++) {
  innerLoop: for (var j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outerLoop; // This will break out of the outer loop
    }
    console.log('i:', i, 'j:', j);
  }
}

Output:
i: 0 j: 0
i: 0 j: 1
i: 0 j: 2
i: 1 j: 0

In the above example we have a nested for loop with two label: outLoop and innerLoop. When the condition i == 1 && j == 1 is met, the break statement with the label outerloop is executed, causing the program to break out of the outer loop entirely. This allows you to control the flow of execution in a more granular way.

Note that labels in JavaScript are identifiers followed by a colon. They can be placed before any statement, but they are typically used with loop statements. It’s important to use labels judiciously and only when necessary, as excessive use of labels can make code harder to read and maintain.