JavaScript Continue Statement

The continue statement in JavaScript is used to skip the current iteration of a loop and continue with the next one. It is often used to skip over specific values or conditions within a loop.

Basic Syntax

The basic syntax for using the continue statement in a loop is as follows:

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

In this example, the loop will skip the iteration when the value of i is 3.


Using Continue in a For Loop

The continue statement can be used inside a for loop to skip specific iterations.

Example: Skip Even Numbers
Try yourself
        
            for (let i = 0; i < 10; i++) {
    if (i % 2 === 0) {
        continue;
    }
    console.log(i);
}
// Output: 1, 3, 5, 7, 9
        
    

This example demonstrates how to skip even numbers in a loop using the continue statement.


Using Continue in a While Loop

The continue statement can also be used inside a while loop to control iterations.

Example: Skip Multiples of 3
Try yourself
        
            let i = 0;
while (i < 10) {
    i++;
    if (i % 3 === 0) {
        continue;
    }
    console.log(i);
}
// Output: 1, 2, 4, 5, 7, 8, 10
        
    

This example shows how to skip multiples of 3 in a while loop using the continue statement.


Using Continue in a Nested Loop

The continue statement can be used in nested loops to control iterations at different levels.

Example: Skip Inner Loop Iteration
Try yourself
        
            for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        if (j === 1) {
            continue;
        }
        console.log(`i = ${i}, j = ${j}`);
    }
}
// Output: i = 0, j = 0
//         i = 0, j = 2
//         i = 1, j = 0
//         i = 1, j = 2
//         i = 2, j = 0
//         i = 2, j = 2
        
    

This example demonstrates how to use the continue statement in a nested loop to skip iterations in the inner loop.


Important Notes

Here are some important notes and best practices when using the continue statement in JavaScript:


Summary

The continue statement is a powerful tool for controlling loop iterations in JavaScript. By understanding how to use it effectively, you can write more efficient and readable code.