Summary
The break statement terminates the current loop, {{jsxref("Statements/switch", "switch")}}, or {{jsxref("Statements/label", "label")}} statement and transfers program control to the statement following the terminated statement.
Syntax
break [label];
-
label
- Optional. Identifier associated with the label of the statement. If the statement is not a loop or {{jsxref("Statements/switch", "switch")}}, this is required.
Description
The break
statement includes an optional label that allows the program to break out of a labeled statement. The break
statement needs to be nested within the referenced label. The labeled statement can be any {{jsxref("Statements/block", "block")}} statement; it does not have to be preceded by a loop statement.
Examples
The following function has a break
statement that terminates the {{jsxref("Statements/while", "while")}} loop when i
is 3, and then returns the value 3 * x
.
function testBreak(x) { var i = 0; while (i < 6) { if (i == 3) { break; } i += 1; } return i * x; }
The following code shows how break
statements are used with labeled blocks.
outer_block:{ inner_block:{ console.log ('1'); break outer_block; // breaks out of both inner_block and outer_block console.log (':-('); // skipped } console.log ('2'); // skipped }
block_1:{ console.log ('1'); break block_2; // throws an error because block_2 is an unknown label since this break statement isn't nested within block_2 } block_2:{ console.log ('2'); }
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 1st Edition | Standard | Initial definition. Unlabeled version. |
ECMAScript 3rd Edition | Standard | Labeled version added. |
{{SpecName('ES5.1', '#sec-12.8', 'Break statement')}} | {{Spec2('ES5.1')}} | |
{{SpecName('ES6', '#sec-break-statement', 'Break statement')}} | {{Spec2('ES6')}} |
Browser compatibility
{{ CompatibilityTable() }}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} |
See also
- {{jsxref("Statements/continue", "continue")}}
- {{jsxref("Statements/label", "label")}}
- {{jsxref("Statements/switch", "switch")}}