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
What is the difference between break and continue statements in JavaScript?
JavaScript provides two important control statements for modifying loop execution: break and continue. While both affect loop flow, they serve different purposes.
break Statement
The break statement is used to exit a loop completely, terminating the entire loop execution and transferring control to the statement immediately following the loop.
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!
Notice how the loop exits completely when x reaches 5, and execution continues with the statement after the loop.
continue Statement
The continue statement skips the rest of the current iteration and immediately moves to the next iteration of the loop. Unlike break, it doesn't exit the loop entirely.
Example
<html>
<body>
<script>
var x = 1;
document.write("Entering the loop<br />");
while (x < 10) {
x = x + 1;
if (x == 8) {
continue; // skip rest of the loop body
}
document.write(x + "<br />");
}
document.write("Exiting the loop!<br />");
</script>
</body>
</html>
Entering the loop 2 3 4 5 6 7 9 10 Exiting the loop!
Notice how the number 8 is skipped in the output, but the loop continues executing until the condition becomes false.
Comparison
| Statement | Action | Loop Execution |
|---|---|---|
break |
Exits loop completely | Terminates immediately |
continue |
Skips current iteration | Continues to next iteration |
Conclusion
Use break when you need to exit a loop completely based on a condition, and continue when you want to skip specific iterations while keeping the loop running.
