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 value 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:
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