JavaScript break statement
JavaScript Statements Reference Manual
Examples
The examples we use the break statement in a loop.
Loop code block, exiting the loop variable i is "3":
var i;
for (i = 0; i <5; i ++) {
if (i == 3) {
break;
}
text + = "The number is" + i + "<br>";
}
text output is:
The number is 1
The number is 2
try it"
At the bottom of this article contains more examples.
Definition and Usage
break statement is used to exit the switch statement or loop statements (for, for ... in, while, do ... while).
When a break statement is used to switch statement, will switch out of a block of code, code execution is halted.
When the break statement is used to loop when the loop terminates and execution cycle after the code (if any).
The same statement can be used to break an optional label references for out of the code block. (See the following "more examples").
Note: break statement (with no label references), it can only be used in loops or switch.
Browser Support
Statements | |||||
---|---|---|---|---|---|
break | Yes | Yes | Yes | Yes | Yes |
grammar
Using the optional label references:
technical details
JavaScript version: | 1.0. JavaScript 1.2 supports optional label. |
---|
More examples
Examples
This example uses the break statement in a while loop statement.
Loop code block, in exiting the loop i is equal to "3":
var i = 0;
while (i <5) {
text + = "<br> The number is" + i;
i ++;
if (i == 3) {
break;
}
}
text output is:
The number is 1
The number is 2
try it"
Examples
Out of the switch statement block, ensure that only one case block execution:
switch (new Date (). getDay ()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
}
day output is:
try it"
Examples
Use the break statement in reference label for jump code block:
var text = "";
list: {
text + = cars [0] + "<br>";
text + = cars [1] + "<br>";
text + = cars [2] + "<br>";
break list;
text + = cars [3] + "<br>";
}
text output is:
Volvo
Saab
try it"
Examples
Use the break statement in the label references for out of nested loops:
var i, j;
Loop1: // first loop label "Loop1"
for (i = 0; i <3; i ++) {
text + = "<br>" + "i =" + i + ", j =";
Loop2: // The second loop tag "Loop2"
for (j = 10; j <15; j ++) {
if (j == 12) {
break Loop2;
}
. Document.getElementById ( "demo") innerHTML = text + = j + "";
}
}
text output is;
i = 1, j = 10 11
i = 2, j = 10 11
try it"
Related Pages
JavaScript Tutorials: JavaScript Break and Continue
JavaScript Tutorials: JavaScript cycle
JavaScript Tutorials: JavaScript the While loop
JavaScript Tutorials: JavaScript Continue statement
JavaScript Reference Manual: JavaScript for statements
JavaScript Reference Manual: JavaScript the while statement
JavaScript Statements Reference Manual