The continue statement: Skipping iterations
You'll learn how to skip the rest of the current loop iteration and jump straight to the next cycle using continue.
What is continue?
The continue statement lets you skip the remaining code in the current loop iteration and immediately jump to the next iteration. Unlike break, which exits the loop entirely, continue just skips ahead—the loop keeps running.
Think of it like skipping a song on a playlist. You don't stop listening to music altogether (that would be break), you just move to the next track and keep going.
How continue Works
When JavaScript encounters continue, it:
- Stops executing the rest of the code in the current iteration
- Jumps to the loop's next iteration check (incrementing in
forloops, re-evaluating the condition inwhileloops)
Basic Example
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip when i is 3
}
console.log(i);
}
// Output: 1, 2, 4, 5 (notice 3 is missing)
Practical Use: Filtering While Looping
let numbers = [1, 2, 3, 4, 5, 6];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
continue; // Skip even numbers
}
console.log(numbers[i]); // Only prints odd numbers
}
// Output: 1, 3, 5
With While Loops
let count = 0;
while (count < 5) {
count++;
if (count === 3) {
continue;
}
console.log(count);
}
// Output: 1, 2, 4, 5
Key Takeaway: Use continue to skip the rest of the current iteration and move to the next cycle—the loop continues running, just without executing the remaining code for that particular iteration.