search ]

JavaScript continue Statement: A Complete Guide

The continue statement in JavaScript is used to skip the current iteration of a loop and proceed to the next iteration. It is particularly useful when you need to bypass certain conditions within a loop without terminating the loop entirely.

Using continue in Loops

The continue statement can be used in various loops such as for, while, and do...while to control the flow of the loop based on specific conditions:

for (let i = 0; i < 10; i++) {
    if (i % 2 === 0) {
        continue; // Skip the rest of the loop for even numbers
    }
    console.log(i);
}
// Output: 1, 3, 5, 7, 9

In this example, the loop skips the even numbers and continues with the next iteration for the odd numbers.

The continue statement also works in for...of and for...in loops:

const fruits = ['apple', 'banana', 'cherry', 'date'];

for (const fruit of fruits) {
    if (fruit.length > 5) {
        continue; // Skip fruits with more than 5 characters
    }
    console.log(fruit);
}
// Output: apple, date

Using continue in while Loops

The continue statement can also be used in while loops to skip certain iterations:

let i = 0;
while (i < 10) {
    i++;
    if (i % 2 === 0) {
        continue; // Skip the rest of the loop for even numbers
    }
    console.log(i);
}
// Output: 1, 3, 5, 7, 9

Similar to the for loop, this while loop skips the even numbers and continues with the next iteration for the odd numbers.

When using continue in a while loop, make sure the counter is incremented before the continue statement. In a for loop, continue jumps to the update expression (e.g., i++) automatically. In a while loop, any code after continue is skipped – so if the increment is below it, the counter never changes and you get an infinite loop.

Using continue in do…while Loops

The continue statement works in do…while loops in the same way, allowing you to skip specific iterations based on a condition:

let i = 0;
do {
    i++;
    if (i % 2 === 0) {
        continue; // Skip the rest of the loop for even numbers
    }
    console.log(i);
} while (i < 10);
// Output: 1, 3, 5, 7, 9

Using continue with Labels

In addition to its use in loops, the continue statement can also be used with labels to control the flow of nested loops more precisely:

outerLoop: for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        if (i === j) {
            continue outerLoop; // Skip the rest of the outer loop iteration
        }
        console.log('i =', i, 'j =', j);
    }
}
// Output: 
// i = 0 j = 1
// i = 0 j = 2
// i = 1 j = 0
// i = 1 j = 2
// i = 2 j = 0
// i = 2 j = 1

In this example, the continue statement with the label outerLoop skips the current iteration of the outer loop when i equals j.

Why continue Does Not Work in forEach

Just like break, the continue statement cannot be used inside a forEach() callback. It will throw a syntax error because continue can only operate within a loop it is directly contained in – not inside a callback function.

// This will throw: "Illegal continue statement"
[1, 2, 3, 4, 5].forEach(num => {
    if (num % 2 === 0) {
        continue; // SyntaxError
    }
    console.log(num);
});

To achieve the same skip behavior with forEach(), use return instead. Since each iteration runs its own callback, return exits only the current callback and effectively skips to the next element:

[1, 2, 3, 4, 5].forEach(num => {
    if (num % 2 === 0) {
        return; // Skips to the next element
    }
    console.log(num);
});
// Output: 1, 3, 5

Difference Between break and continue

Both break and continue statements in JavaScript are used to control the flow of loops. The break statement terminates the loop entirely, while continue skips only the current iteration and proceeds with the next one.

Here’s a more comprehensive post about the JavaScript break statement.

Here is a side-by-side comparison:

// break example
for (let i = 0; i < 5; i++) {
    if (i === 3) break;
    console.log(i);
}
// Output: 0, 1, 2

// continue example
for (let i = 0; i < 5; i++) {
    if (i === 3) continue;
    console.log(i);
}
// Output: 0, 1, 2, 4

Both statements help manage the execution of loops and can improve code readability and efficiency when used appropriately.

Best Practices

While the continue statement can be a powerful tool for controlling loop execution, it should be used carefully to maintain code readability and prevent unexpected behavior. Here are some best practices:

  • Clear Conditions: Use continue when you have a clear and logical condition for skipping iterations. This helps in understanding the flow of the loop and makes the code more readable.
  • Avoid Overuse: Overusing continue can make the code harder to follow. Ensure that its use is justified and adds value to the loop’s logic.
  • Watch the Increment in while Loops: Always place the counter increment before any continue statement in while and do...while loops to avoid infinite loops.
  • Use with Labels Sparingly: When working with nested loops, labeled continue can help control the flow precisely. However, keep the use of labels minimal to avoid confusion.
  • Use return in forEach: If you need skip behavior inside forEach(), use return instead of continue.

FAQs

Common questions about the JavaScript continue statement:

What is the difference between break and continue in JavaScript?
break terminates the entire loop and moves execution to the first statement after the loop. continue skips only the current iteration and proceeds to the next one. Use break when you want to stop looping altogether and continue when you want to skip specific iterations.
Can I use continue inside a forEach callback?
No. Using continue inside a forEach() callback throws a syntax error because continue can only be used inside a loop construct. To achieve the same skip behavior, use return inside the callback instead - it exits the current callback and moves to the next element.
Why does continue cause an infinite loop in my while loop?
This usually happens when the counter increment is placed after the continue statement. In a while loop, continue jumps back to the condition check and skips everything below it, including the increment. Move the increment before the continue to fix this. In a for loop, this is not an issue because the update expression runs automatically.
Does continue work in for...of and for...in loops?
Yes. The continue statement works in all standard loop constructs: for, while, do...while, for...of, and for...in. The only iteration method where it does not work is forEach(), which uses a callback function rather than a loop construct.
What does a labeled continue statement do?
A labeled continue skips the current iteration of a specific outer loop in a nested loop structure. Without a label, continue affects only the innermost loop. By referencing a label (e.g., continue outerLoop), you skip the rest of the outer loop's current iteration and move to its next one.

Summary

The continue statement in JavaScript is a powerful tool for controlling the flow of loops by skipping specific iterations and moving to the next one. It works in all standard loop constructs – for, while, do...while, for...of, and for...in – but not inside forEach() callbacks, where return serves as the equivalent.

By understanding and applying the continue statement correctly, you can manage the execution of your loops more effectively. Mastering its use alongside other control statements like break enhances your ability to write clean and efficient JavaScript code.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo