What are label statements in JavaScript?

JavaScript label statements are used to prefix a label to an identifier. A label can be used with break and continue statements to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code.

Syntax

labelName: statement

Where labelName is any valid JavaScript identifier, and statement can be any JavaScript statement, typically a loop.

Using Labels with break Statement

Labels allow you to break out of nested loops by specifying which loop to exit:

<html>
  <body>
    <script>
      document.write("Entering the loop!<br /> ");

      outerloop: // This is the label name
        for (var i = 0; i < 5; i++) {
          document.write("Outerloop: " + i + "<br />");

          innerloop:
            for (var j = 0; j < 5; j++) {
              if (j > 3) break; // Quit the innermost loop
              if (i == 2) break innerloop; // Do the same thing
              if (i == 4) break outerloop; // Quit the outer loop
              document.write("Innerloop: " + j + " <br />");
            }
        }
        document.write("Exiting the loop!<br /> ");
    </script>
  </body>
</html>
Entering the loop!
Outerloop: 0
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 1
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 2
Outerloop: 3
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 4
Exiting the loop!

Using Labels with continue Statement

Labels can also be used with continue to skip to the next iteration of a specific loop:

<html>
  <body>
    <script>
      document.write("Entering the loop!<br /> ");

      outerloop: // This is the label name
      for (var i = 0; i < 3; i++) {
        document.write("Outerloop: " + i + "<br />");
        for (var j = 0; j < 5; j++) {
          if (j == 3) {
            continue outerloop;
          }
          document.write("Innerloop: " + j + "<br />");
        }
      }
      document.write("Exiting the loop!<br /> ");
    </script>
  </body>
</html>
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!

Key Points

  • Labels are identifiers followed by a colon (:)
  • They work only with break and continue statements
  • break labelName exits the labeled statement completely
  • continue labelName skips to the next iteration of the labeled loop
  • Labels are rarely used in modern JavaScript but useful for complex nested loops

Conclusion

JavaScript label statements provide precise control over nested loops using break and continue. While not commonly used, they offer a clean solution for complex loop control scenarios.

Updated on: 2026-03-15T22:02:44+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements