JS Continue

JavaScript continue Statement

While the break statement can be used to completely quit a loop, the continue statement is used to skip the current iteration and move on to the next one.

When continue is executed, it immediately stops running the code for the current iteration and jumps back up to check the loop's condition to start a new iteration.


Example 1: Skipping Items in a for...of Loop

Here you can see a practical example of the continue statement. Our approach is to simply skip every car that is not black and only consider all the others that are made in the year 2020 or later.

Using continue to Filter Data

for (let car of cars) {
    // Skip this iteration if the car is NOT black
    if (car.color !== "black") {
        continue;
    }
    if (car.year >= 2020) {
        console.log("We could get this one:", car);
    }
}

The code evaluates each car. If the color isn't black, continue is triggered, and the rest of the loop block (the year check) is skipped entirely for that specific car!


⚠️ Be Careful with continue in a while Loop

Without running it, what do you think the next code snippet does? The intent is to log only the odd numbers to the console.

The Infinite Loop Trap

// let's only log the odd numbers to the console
let i = 1;
while (i < 50) {
    if (i % 2 === 0) {
        continue;
    }
    console.log(i);
    i++;
}

Warning: It logs 1, and then it gets you stuck in an infinite loop! Because continue gets hit before the value of i changes (the i++ is skipped), it will evaluate 2 % 2 === 0, run into continue again, and again, and so on.

Fixing the while Loop

This can be fixed by moving the i++ up before the continue statement, and then subtracting 1 from i when logging it, like this:

Fixed while Loop

let i = 1;
while (i < 50) {
    i++;
    if ((i - 1) % 2 === 0) {
        continue;
    }
    console.log(i - 1);
}

The Best Way: Use a for Loop

But again, there is a much better way without using continue here. The chance of error is a lot smaller, and the code is shorter and more readable:

for (let i = 1; i < 50; i = i + 2) {
    console.log(i);
}

When to Use break and continue

The value of break and continue usually comes in when you are looping over large data sets, possibly coming from outside your application (like an API or a database). Here you'll have less influence to apply other types of control directly in the loop declaration. Using break and continue is not a best practice for simple basic examples, but it's a great way to get familiar with the concepts!


Exercise

?

What does the continue statement do inside a loop?