JavaScript Label Statement

In JavaScript a label is simply an identifier followed by a color (:) which is applied to a statement or a block of code. The basic syntax of label function would is :
 label:
Or
 label {
   // Scope of the block
 }
Where :

  • The label or label name is an unique identifier for referring to label  that are specified with the break or continue statement
  • The curly bracket {...} is optional, which is used to identify the block of statement that are in labelled with.

It is mainly used with the break and continue statement. The continue statement can only be used to skip one loop iteration, but in case of break statement with a label reference the code flow can be jumped out of any code block.

Lets see an example of label with break statement :

Example 1 :
<!DOCTYPE html>
<html>
<head>
  <title>Label with break statement</title>
</head>
<body>
  <script>
    brk = "<br/>";
    OuterBlock:
      for(var i = 0; i <5; i++) {
        document.write("This is OuterBlock : ", i, brk);
        InnerBlock:
        for(var a = 0; a < 2; a++) {
          if (i == 3) {break InnerBlock;}
            document.write("This is InnerBlock : ", a, brk);
        }
      }
  </script>
</body>
</html>
Output :


Example 2 :
<!DOCTYPE html>
<html>
<head>
  <title>Label with continue statement</title>
</head>
<body>
  <script>
    brk = "<br/>";
    OuterBlock:
      for(var i = 0; i <5; i++) {
        document.write("This is OuterBlock : ", i, brk);
        if (i == 3) {continue OuterBlock;}
        InnerBlock:
          for(var a = 0; a < 2; a++) {
            document.write("This is InnerBlock : ", a, brk);
          }
      }
  </script>
</body>
</html>
Output :



Next Topic :