0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Labeled Statement in JavaScript: Syntax and Examples

In JavaScript, a labeled statement assigns a name to a loop or block, allowing you to use break or continue to control flow outside the immediate loop. You write a label followed by a colon before the statement, then refer to it in break or continue to jump to or skip specific parts of nested loops.
📐

Syntax

A labeled statement consists of a label name followed by a colon and a statement (usually a loop or block). You can then use break or continue with that label to control the flow.

  • labelName: statement — defines the label.
  • break labelName; — exits the labeled statement.
  • continue labelName; — skips to the next iteration of the labeled loop.
javascript
labelName: for (let i = 0; i < 3; i++) {
  // code block
}
💻

Example

This example shows how to use a labeled statement to break out of an outer loop from inside an inner loop.

javascript
outerLoop: for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 3; j++) {
    if (i === 2 && j === 2) {
      break outerLoop; // exits the outer loop
    }
    console.log(`i = ${i}, j = ${j}`);
  }
}
console.log('Loop ended');
Output
i = 1, j = 1 i = 1, j = 2 i = 1, j = 3 i = 2, j = 1 Loop ended
⚠️

Common Pitfalls

Common mistakes include:

  • Using labels on statements that are not loops or blocks, which is allowed but rarely useful.
  • Trying to use continue with a label on a non-loop statement, which causes errors.
  • Overusing labels, which can make code harder to read and maintain.

Labels should be used sparingly and only when you need to control nested loops clearly.

javascript
wrongLabel: {
  console.log('Inside block');
  // continue wrongLabel; // This will cause a syntax error because continue only works with loops
}

correctLabel: for (let i = 0; i < 2; i++) {
  if (i === 1) {
    continue correctLabel; // This works because it's a loop
  }
  console.log(i);
}
Output
0
📊

Quick Reference

KeywordDescriptionUsage Example
labelName:Defines a label for a statementmyLabel: for(...) {...}
break labelName;Exits the labeled statement immediatelybreak myLabel;
continue labelName;Skips to next iteration of labeled loopcontinue myLabel;

Key Takeaways

Use labeled statements to name loops or blocks for targeted break or continue.
Labels help control flow in nested loops by specifying which loop to affect.
Only use continue with labels on loops, not on blocks or other statements.
Avoid overusing labels to keep code clear and easy to read.
Labeled statements improve control flow but should be used carefully.