JavaScript break and continue Statements
The break statement is used to exit a loop.
The continue statement is used to skip an iteration in a loop.
break Statement
We have already seen the break statement in previous sections of this tutorial. It is used to exit a switch() statement.
The break statement can also be used to exit a loop.
After the break statement exits the loop, it continues executing the code after the loop (if any):
Example
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}
Since this if statement contains only one line of code, the curly braces can be omitted:
for (i=0;i<10;i++)
{
if (i==3) break;
x=x + "The number is " + i + "<br>";
}
continue Statement
The continue statement interrupts the current iteration within a loop and continues with the next iteration. The following example skips the value 3:
for Example
for (i=0;i<=10;i++)
{
if (i==3) continue;
x=x + "The number is " + i + "<br>";
}
while Example
while (i < 10){
if (i == 3){
i++; // Adding i++ to avoid an infinite loop
continue;
}
x= x + "The number is " + i + "<br>";
i++;
}
JavaScript Labels
As you saw in the chapter on the switch statement, JavaScript statements can be labeled.
To label a JavaScript statement, prepend it with a colon:
label:
statements
The break and continue statements are the only ones that can jump out of a code block.
Syntax:
break labelname;
continue labelname;
The continue statement (with or without a label reference) can only be used within a loop.
The break statement (without a label reference) can only be used within a loop or switch.
With a label reference, the break statement can be used to exit any JavaScript code block:
Example
cars=["BMW","Volvo","Saab","Ford"];
list:
{
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
break list;
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
}