How to Skip Iteration in Loop JavaScript: Simple Guide
In JavaScript, you can skip the current iteration of a loop using the
continue statement. When continue runs inside a loop, it immediately stops the current cycle and moves to the next one.Syntax
The continue statement is used inside loops like for, while, or do...while. When JavaScript encounters continue, it skips the rest of the code in the current loop iteration and jumps to the next iteration.
continue;— skips to the next iteration immediately.
javascript
for (let i = 0; i < 5; i++) { if (i === 2) { continue; // skip when i is 2 } console.log(i); }
Output
0
1
3
4
Example
This example shows a loop from 0 to 4. When the number is 2, the continue statement skips printing it, so 2 does not appear in the output.
javascript
for (let i = 0; i < 5; i++) { if (i === 2) { continue; // skip printing 2 } console.log(i); }
Output
0
1
3
4
Common Pitfalls
One common mistake is using continue outside of loops, which causes an error. Another is forgetting that continue skips only the current iteration, not the whole loop. Also, placing continue incorrectly can cause unexpected behavior.
Wrong example (using continue outside loop):
javascript
if (true) { // continue; // This will cause a syntax error because continue must be inside a loop } // Correct usage inside a loop: for (let i = 0; i < 3; i++) { if (i === 1) { continue; // skips iteration when i is 1 } console.log(i); }
Output
0
2
Quick Reference
Use continue to skip the rest of the current loop iteration and move to the next one.
- Works in
for,while, anddo...whileloops. - Must be inside a loop, or it causes an error.
- Does not stop the whole loop, only skips current iteration.
| Keyword | Purpose | Usage |
|---|---|---|
| continue | Skip current iteration | Inside loops only |
| break | Exit entire loop | Inside loops only |
| return | Exit function | Inside functions |
Key Takeaways
Use
continue inside loops to skip the current iteration and move to the next.continue must be inside a loop; otherwise, it causes a syntax error.It only skips the current iteration, not the whole loop.
Place
continue carefully to avoid skipping important code unintentionally.