JavaScript break statement with Example code

  • by

JavaScript break statement used in switch statement and loops to terminates it. In a switch, it stops the execution of more code inside the switch. In loop, it will break current loop.

break;

If the statement is not a loop or switch, label is required.

break [label];

JavaScript break examples

Simple example code to break out of JavaScript code block.

Break in while loop

Break out of a loop when i is 3:

<!DOCTYPE html>
<html>
<head>

  <script>

    var i = 0;

    while (i < 6) {
      console.log(i)

      if (i == 3) {
        console.log("Break")
        break;
      }
      i += 1;
    }    

  </script>
</head>
<body>

</body>
</html>

Output:

JavaScript break statement

Break in switch statements

Break out of a switch block when a case is true:

const food = "sushi";

switch (food) {
  case "sushi":
    console.log("Sushi is originally from Japan.");
    break;
  case "pizza":
    console.log("Pizza is originally from Italy.");
    break;
  default:
    console.log("I have never heard of that dish.");
    break;
}

Do comment if you have any doubts or suggestions on this JS break code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.