JavaScript Break and Continue Statement
The break statement is used to break out of the loop.
continue is used to skip an iteration in the loop.
break Statement
We have already seen the break statement in the previous chapters of this tutorial. It is used to jump out of the switch() statement.
The break statement can be used to break out of the loop.
After the break statement breaks out of the loop, it will continue to execute 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 has 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 iteration in the loop. If the specified condition occurs, then continue to the next iteration in the loop. This example skips the value 3:
Example
for (i=0;i<=10;i++) { if (i==3) continue; x=x + "The number is "+ i + "<br>"; }
JavaScript Tags
As you saw in the chapter on switch statements, JavaScript statements can be marked.
To mark JavaScript statements, add a colon before the statement:
label:
statements
The break and continue statements are just statements that can jump out of the code block.
Grammar:
break labelname;
continue labelname;
The continue statement (referenced with or without label) can only be used in a loop.
The break statement (quoted without a label) can only be used in a loop or switch.
By tag reference, the break statement can be used to jump out of any JavaScript code block:
Example
cars=["BMW","Dodge","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>"); }