There are certain conditions when we need to break out of a loop before the complete loop gets executed. Or, in some cases we want to break out of the loop because there may be chances of an error. With the execution of the break statement, program flow will resume to the next sequential statement following the loop.
Break brings control out, as the statements in the switch case executed. If the break statement were omitted from switch case, the interpreter would execute each and every statement in all the switch case structures.
var x = prompt("Write a number in between 1 to 4");
case "1": alert(‘x is 1’);
case "2": alert(‘x is 2’);
case "3": alert(‘x is 3’);
case "4": alert(‘x is 4’);
default: alert(‘x is not 1, 2, 3 or 4’);
In the previous example, the value of x would determine which message was printed by comparing the value of the variable to the various case statements. If no match were found, the default statement would be executed. The break statement is also used commonly within switch to exit the statement once the appropriate choice is found. However, if we miss the break statement's use will execute all the statements in the switch cases. Just comment break in the previous and see the output.
Let's take a condition; we want to alert/print all the numbers in between 1 to 10 which are not dividable by 2.
strDummy+=i+ ", ";
alert("Number " + strDummy.substring(0, strDummy.length–2) +" are not dividable by 2.");
In the above code we are going through a loop from 1 to 10. We are
Labels are optional parameter provided with break and continue. Without Labels both break and continue works in their natural way.
for (var i = 0; i < 3; i++)
document.write("Outerloop: "+i+"<br />");
for (var j = 0; j < 5; j++)
if (i == 1)
if (j == 3)
document.write("Innerloop: "+j+"<br />");
document.write("All loops done"+"<br />");
In the above code we have two for loops. First loops run three time; while in the second loop
var j = 0 reach to 3 continue outerloop; set the program flow Label 'outerloop:'. In second iteration when i=1 break take us out of the second loop. Program run till 1<3 and we get output as shown figure below.