JavaScript Break Statement

To control the flow of code execution JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively. These statement provides full control to handle loops and switch statements.

The break is special statement that can be used inside the loops. It terminates the current loop and execution control transfer after the end of loop. The basic syntax :
  break;
Or
  break [ label_name ];
Where :

  • The break keyword terminates the current loop.
  • The label keyword is optional, it is basically the label_name which you want to skip.

For Example :
while() {
  break;
}
Example :
<!DOCTYPE html>
<html>
<head>
  <title>Break Statement</title>
</head>
<body>
  <script>
    brk = "<br/>";
    var x = 1;
    while (x <= 10) {
      document.write(x, brk);
      x++;
      if(x == 6) {
        break;
      }
    }
  </script>
</body>
</html>
Output :


The above code will break the while loop when x is equal to 6.


Next Topic :