Break without label
The break statement is used to exit a loop early, breaking out of the enclosing curly braces. The break statement exits out of a loop.
Example
Let’s see an example of break statement in JavaScript without using label −
Live Demo
<html>
<body>
<script>
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>Break with label
Labels are used to control the flow of a program i.e. let’s say using it in a nested for loop to jump to inner or outer loop. You can try to run the following code to use labels to control the flow, with break statement −
Example
Live Demo
<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>