Loading...
Loading...

The Continue Statement in JavaScript

The continue statement in JavaScript is used within loops to skip the current iteration and continue with the next iteration of the loop. It can be particularly useful when you want to ignore certain values while iterating.

How the Continue Statement Works

When the continue statement is encountered, the remaining code within the loop for that particular iteration is skipped, and the control moves to the next iteration of the loop.

Using Continue in a For Loop

for (let i = 0; i < 10; i++) {
    if (i % 2 === 0) {
        continue; // Skip even numbers
    }
    console.log(i); // Logs only odd numbers
}

In this example, the loop iterates from 0 to 9, but the continue statement skips the even numbers, resulting in the output: 1, 3, 5, 7, 9.

Using Continue in a While Loop

let j = 0;
while (j < 10) {
    j++;
    if (j % 3 === 0) {
        continue; // Skip multiples of 3
    }
    console.log(j); // Logs numbers that are not multiples of 3
}

In this example, the continue statement skips the numbers that are multiples of 3, so the output will be 1, 2, 4, 5, 7, 8, 10.

Using Continue in a Nested Loop

for (let i = 1; i <= 3; i++) {
    for (let j = 1; j <= 3; j++) {
        if (j === 2) {
            continue; // Skip when j is 2
        }
        console.log(`i = ${i}, j = ${j}`);
    }
}

This nested loop will print combinations of i and j, skipping any iteration where j is 2. The output will be:

i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 3

Conclusion

The continue statement is a powerful tool in JavaScript that allows developers to manage loop execution effectively. It helps to control the flow of the loop by skipping specific iterations, making your code cleaner and more efficient.

0 Interaction
488 Views
Views
28 Likes
×
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

$ Allow cookies on this site ? (y/n)

top-home