Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the difference between break with a label and without a label in JavaScript?
In JavaScript, the break statement is used to exit loops. Without a label, it exits only the innermost loop. With a label, it can exit any labeled loop, even outer ones in nested structures.
Break Without Label
The break statement without a label exits only the current loop it's inside. It cannot jump out of nested loops to an outer level.
Example
<html>
<body>
<script>
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>
Entering the loop 2 3 4 5 Exiting the loop!
Break With Label
Labels allow you to control program flow in nested loops. You can break out of any labeled loop, including outer loops, by specifying the label name after break.
Syntax
labelName: for (...) {
for (...) {
break labelName; // breaks out of labeled loop
}
}
Example
<html>
<body>
<script>
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>
Entering the loop! Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 2 Outerloop: 3 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 4 Exiting the loop!
Comparison
| Type | Scope | Use Case |
|---|---|---|
break |
Current loop only | Simple loop exit |
break label |
Any labeled loop | Exit nested loops, jump to specific level |
Key Points
- Labels must be placed immediately before the loop statement
- Label names follow JavaScript identifier rules
- Labels work with
breakandcontinuestatements - Use labels sparingly - they can make code harder to read
Conclusion
Use break without labels for simple loop exits. Use labeled break statements when you need to exit multiple nested loops or jump to specific outer levels.
Advertisements
