English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
JavaScript Statements and Variable Declarations
breakstatement terminates the current loop, switch, or label statement, and transfers program control to the statement after the terminating statement.
When the break statement is used with a switch statement, it will exit the switch block. This will stop executing more code or performing case tests within the block.
When using the break statement in a loop, it will break out of the loop and continue executing the code after the loop.
The break statement includes an optionalLabel, theLabelAllows the program to exit a labeled statement (see the following 'More examples').
break label;
var text = ""; for (let i = 0; i < 6; i++) { if (i === 3) { break; } text += "The number is " + i + "<br>"; }Test and see‹/›
All browsers fully support the break statement:
Statement | |||||
break | Is | Is | Is | Is | Is |
Parameter | Description |
---|---|
Label | (Optional) Identifier associated with a statement label. If the statement is not a loop or switch, it is required. |
JavaScript version: | ECMAScript 1 |
---|
The following function has a break statement, when i is3Terminates the while loop and returns the value3 * x:
function testBreak(x) { var i = 0; while (i < 6) { if (i == 3) { break; } i++; } return i * x; }Test and see‹/›
This example exits a switch block to ensure that only one case is executed:
var day; 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; }Test and see‹/›
The following code uses a labeled break statement to 'exit' a JavaScript code block:
outer_block: { inner_block: { document.writeln('1'); break outer_block;// Exit from inner_block and outer_block document.writeln(':-('); // skipped } document.writeln('2'); // skipped }Test and see‹/›
JavaScript Tutorial:JavaScript break and continue
JavaScript Tutorial:JavaScript for Loop
JavaScript Tutorial:JavaScript while Loop
JavaScript Tutorial:JavaScript switch
JavaScript Reference:JavaScript continue Statement
JavaScript Reference: JavaScript for Statement
JavaScript Reference: JavaScript while Statement
JavaScript Reference: JavaScript switch Statement