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
How to break a loop in JavaScript?
The break statement is used to exit a loop immediately and continue executing the code after the loop. When a break is encountered, the loop terminates completely, unlike continue which only skips the current iteration.
Syntax
break;
Breaking a for Loop
The most common use of break is to exit a loop when a certain condition is met:
<!DOCTYPE html>
<html>
<body>
<p id="test"></p>
<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
if (i === 2) {
break;
}
text += "Value: " + i + "<br>";
}
document.getElementById("test").innerHTML = text;
</script>
</body>
</html>
Value: 0 Value: 1
Breaking a while Loop
You can also use break to exit while loops:
<!DOCTYPE html>
<html>
<body>
<p id="while-demo"></p>
<script>
var result = "";
var counter = 0;
while (counter < 10) {
if (counter === 3) {
break;
}
result += "Counter: " + counter + "<br>";
counter++;
}
document.getElementById("while-demo").innerHTML = result;
</script>
</body>
</html>
Counter: 0 Counter: 1 Counter: 2
Breaking Nested Loops
In nested loops, break only exits the innermost loop:
<!DOCTYPE html>
<html>
<body>
<p id="nested-demo"></p>
<script>
var output = "";
for (var i = 0; i < 3; i++) {
output += "Outer loop: " + i + "<br>";
for (var j = 0; j < 3; j++) {
if (j === 1) {
break; // Only breaks inner loop
}
output += " Inner loop: " + j + "<br>";
}
}
document.getElementById("nested-demo").innerHTML = output;
</script>
</body>
</html>
Outer loop: 0 Inner loop: 0 Outer loop: 1 Inner loop: 0 Outer loop: 2 Inner loop: 0
Common Use Cases
| Scenario | Example Use |
|---|---|
| Search Operations | Exit loop when item is found |
| Error Conditions | Stop processing on invalid data |
| Performance | Avoid unnecessary iterations |
Conclusion
The break statement provides an efficient way to exit loops early when specific conditions are met. It works with all loop types and only affects the innermost loop in nested structures.
Advertisements
