In JavaScript, the continue statement is a powerful control flow tool that allows you to skip the current iteration of a loop and move on to the next one. It is often used in conjunction with loops to provide more flexibility and control over the execution of your code.
The continue statement is particularly useful when you want to skip certain iterations based on specific conditions, without terminating the entire loop. By using continue, you can effectively control the flow of your loop and customize the behavior to suit your specific needs.
Let’s take a closer look at how the continue statement works with some examples:
Example 1: Skipping Odd Numbers
for (let i = 1; i <= 10; i++) {
if (i % 2 !== 0) {
continue;
}
console.log(i);
}
In this example, we use a for loop to iterate from 1 to 10. Inside the loop, we check if the current number (i
) is odd using the modulus operator (%
). If the number is odd, we use the continue statement to skip that iteration and move on to the next one. As a result, only the even numbers from 1 to 10 (2, 4, 6, 8, 10) will be printed to the console.
Example 2: Skipping Specific Values
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 3 || numbers[i] === 7) {
continue;
}
console.log(numbers[i]);
}
In this example, we have an array of numbers from 1 to 10. We use a for loop to iterate over each element in the array. Inside the loop, we check if the current number is equal to 3 or 7. If it is, we use the continue statement to skip that iteration. As a result, the numbers 3 and 7 will be skipped, and the remaining numbers (1, 2, 4, 5, 6, 8, 9, 10) will be printed to the console.
Example 3: Skipping Iterations Based on a Condition
let i = 0;
while (i < 5) {
i++;
if (i === 3) {
continue;
}
console.log(i);
}
In this example, we use a while loop to iterate as long as the condition i < 5
is true. Inside the loop, we increment the value of i
by 1. If i
is equal to 3, we use the continue statement to skip that iteration. As a result, the number 3 will be skipped, and the remaining numbers (1, 2, 4, 5) will be printed to the console.
The continue statement can be used with any type of loop, including for, while, and do…while loops. It provides a powerful mechanism to control the flow of your code and skip iterations based on specific conditions.
It’s important to use the continue statement judiciously and ensure that it enhances the readability and maintainability of your code. Overusing or misusing the continue statement may lead to complex and hard-to-understand code.
In summary, the continue statement in JavaScript allows you to skip the current iteration of a loop and move on to the next one. It is a versatile tool that empowers you to customize the behavior of your loops and make your code more efficient and concise.