JavaScript break and continue Statements Explained
In JavaScript, break and continue are control flow keywords used inside loops to alter their behavior.
1. break Statement – Exit the loop early
- Stops the loop completely when a certain condition is met.
- Useful when you want to exit a loop prematurely.
Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // Exit loop when i is 3
}
console.log("Value: " + i);
}
Output
Value: 1
Value: 2
Value: 2
Explanation:
When i becomes 3, break stops the loop immediately.
2. continue Statement – Skip to the next loop iteration
- Skips the current iteration, but continues the loop.
- Used when you want to ignore certain conditions but keep looping.
Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip the rest when i is 3
}
console.log("Number: " + i);
}
Output
Number: 1
Number: 2
Number: 4
Number: 5
Number: 2
Number: 4
Number: 5