HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Break out of a loop when i is 3
The break
statement breaks out of a switch or a loop.
In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch.
In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).
The break
statement can use a label reference, to break out of any JavaScript code block (see "More Examples"
below).
Without a label, break can only be used inside a loop or a switch.
Using the optional label reference:
Break out of a switch block when a case is true:
let 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;
}
Break out of a list:
let text = "";
const cars = ["BMW", "Volvo", "Saab", "Ford"];
list: {
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
break list;
text += cars[3] + "<br>";
}
Break out of a nested loop:
// The first for loop is labeled "Loop1"
Loop1:
for (let i = 0; i < 3; i++) {
// The second for loop is labeled "Loop2"
Loop2:
for (let i = 10; i < 15; i++) {
if (i === 12) break Loop1;
}
}
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
break
is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |