Javascript continue statement
Created By: chatGPT
The continue statement in JavaScript allows you to skip the current iteration of a loop and proceed to the next iteration. This is particularly useful when you want to bypass certain conditions inside loops without terminating the entire loop. The continue statement can be used in for, while, and do...while loops.
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // This will log only odd numbers
}
In the example above, the loop iterates from 0 to 9. When the current value of
i
is even, the continue statement is executed, which causes JavaScript to skip the console.log(i)
line and move on to the next iteration. As a result, only odd numbers from 1 to 9 are printed.let count = 0;
while (count < 10) {
count++;
if (count % 3 === 0) {
continue; // Skip multiples of 3
}
console.log(count);
}
In this while loop example, we increment the
count
variable until it reaches 10. If count
is a multiple of 3 (i.e., 3
, 6
, or 9
), the continue statement is executed, thereby skipping the console.log(count)
line. Thus, the output will display all numbers from 1 to 10 except the multiples of 3.// Using continue in a do...while loop
let n = 0;
do {
n++;
if (n === 5) {
continue; // This will skip logging when n equals 5
}
console.log(n);
} while (n < 10);
In the do...while loop example, we also check if
n
equals 5. If it does, we use the continue statement to skip the console.log(n)
when n
is 5, ensuring that 5
will not be logged. This allows us to perform checks and control the flow of the loop effectively.for (let j = 0; j < 10; j++) {
if (j < 5) {
continue; // Skip numbers less than 5
}
console.log(j); // Outputs numbers from 5 to 9
}