break
Terminates the nearest enclosing loop or switch, optionally to a label.
Syntax
break;
break label;
Examples
for (let i = 0; i < 10; i++) {
if (i === 3) break;
console.log(i);
}
Output
0
1
2
outer:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) break outer;
console.log(i, j);
}
}
Output
0 0
const x = 2;
switch (x) {
case 2:
console.log("two");
break;
default:
console.log("other");
}
Output
two
Notes
- Without a label, `break` exits only the innermost loop or `switch`.
- A labeled `break` can exit an outer loop from within nested loops.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |