How to Use Continue in JavaScript: Syntax and Examples
In JavaScript, the
continue statement skips the current iteration of a loop and moves to the next one. It is used inside loops like for, while, or do...while to skip specific steps without exiting the loop.Syntax
The continue statement is used inside loops to skip the rest of the current iteration and jump to the next one.
It can be used in these loop types: for, while, and do...while.
Optionally, in labeled loops, you can specify a label to continue an outer loop.
javascript
continue; // Or with a label: continue labelName;
Example
This example shows how continue skips printing even numbers in a for loop.
javascript
for (let i = 1; i <= 5; i++) { if (i % 2 === 0) { continue; // Skip even numbers } console.log(i); }
Output
1
3
5
Common Pitfalls
One common mistake is using continue outside of loops, which causes an error.
Another is forgetting that continue only skips the current iteration, not the whole loop.
Also, using continue in nested loops without labels only affects the innermost loop.
javascript
/* Wrong: continue outside loop causes error */ // continue; // SyntaxError /* Right: continue inside loop */ for (let i = 0; i < 3; i++) { if (i === 1) { continue; // skips when i is 1 } console.log(i); } /* Using labels to continue outer loop */ outerLoop: for (let i = 0; i < 2; i++) { for (let j = 0; j < 3; j++) { if (j === 1) { continue outerLoop; // skips to next i } console.log(`i=${i}, j=${j}`); } }
Output
0
2
i=0, j=0
i=1, j=0
Quick Reference
- Use: To skip the rest of the current loop iteration.
- Works with: for, while, do...while loops.
- Labels: Use with labels to continue outer loops.
- Note: Cannot be used outside loops.
Key Takeaways
The continue statement skips the current loop iteration and moves to the next one.
Use continue only inside loops like for, while, or do...while.
In nested loops, use labels with continue to affect outer loops.
Using continue outside loops causes a syntax error.
Continue helps control loop flow without exiting the entire loop.