JavaScript Break and Continue
8 April 2025 | Category: JavaScript
JavaScript provides two keywords to control loop execution:
- đ´
break
â Exits the loop completely. - đ
continue
â Skips the current iteration and jumps to the next one.
𧨠JavaScript break
Statement
The break
statement stops the loop immediately, even if the condition is still true.
â Syntax
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
Output:
0
1
2
3
4
đ As soon as i
becomes 5, the loop stops.
đ JavaScript continue
Statement
The continue
statement skips the current loop iteration, and continues with the next one.
â Syntax
for (let i = 0; i < 10; i++) {
if (i === 5) {
continue;
}
console.log(i);
}
Output:
0
1
2
3
4
6
7
8
9
đ When i
is 5, the loop skips console.log(i)
and moves to the next iteration.
đ Using with while
Loop
Both break
and continue
work the same way inside a while
loop.
Example with break
:
let i = 0;
while (i < 10) {
if (i === 5) {
break;
}
console.log(i);
i++;
}
Example with continue
:
let i = 0;
while (i < 10) {
i++;
if (i === 5) {
continue;
}
console.log(i);
}
đĄ When to Use
Statement | Use Case Example |
---|---|
break | Stop the loop early (e.g., on condition) |
continue | Skip specific values (e.g., filter values) |
â Real-World Example: Stop at a Target Value
let numbers = [10, 20, 30, 40, 50];
for (let num of numbers) {
if (num === 30) {
break;
}
console.log(num);
}
Output:
10
20
đ§ž Summary
Keyword | Behavior |
---|---|
break | Exits the loop completely |
continue | Skips current iteration, continues |