Break and Continue Statement in Loops
What is break Statement?
- Used to stop a loop completely
- Loop ends immediately when condition is met
Example: Break in For Loop
for (let i = 0; i < 20; i++) {
if (i == 11) {
break;
}
console.log(i);
}
Output:
0 to 10
When to Use Break?
- Stop loop at a specific condition
- Example:
- Stop at user input
- Stop when value is found
- Stop based on date/time
What is continue Statement?
- Used to skip current iteration
- Loop continues with next iteration
Example: Continue in For Loop
for (let i = 0; i <= 10; i++) {
if (i == 4) {
continue;
}
console.log(i);
}
Output:
0 1 2 3 5 6 7 8 9 10
(4 is skipped)
Key Difference
| Stops loop completely | Skips one step only |
| Loop ends | Loop continues |
Example: While Loop with Break & Continue
let i = 0;
while (i < 10) {
i++;
if (i == 3) {
continue;
}
if (i == 8) {
break;
}
console.log(i);
}
Output:
1 2 4 5 6 7
Example: Do While Loop
let i = 0;
do {
i++;
if (i == 3) {
continue;
}
if (i == 8) {
break;
}
console.log(i);
} while (i < 10);
Output:
1 2 4 5 6 7
Common Mistakes
Mistake 1: Wrong Placement of continue
console.log(i);
if(i == 4){
continue;
}
This will still print 4.
Correct:
if(i == 4){
continue;
}
console.log(i);
Mistake 2: Forgetting Increment
while(i < 10){
if(i == 3){
continue;
}
}
This creates an infinite loop.
Always update variable:
i++;
Mistake 3: Confusing Break and Continue
- Break stops everything
- Continue skips only one step
Can We Use Both Together?
Yes, both can be used in the same loop.