The continue
statement skips the current iteration of the loop and proceeds to the next iteration.
Here's a brief example to demonstrate the continue
statement. You can read the rest of the tutorial to learn more.
Example
// program to check for odd numbers
for (let i = 1; i <= 5; i++) {
// skip the iteration if i is even
if (i % 2 === 0) {
continue;
}
console.log(i);
}
// Output:
// 1
// 3
// 5
Here, continue
skips the rest of the loop's body when i is even. Thus, only odd numbers are printed.
Working of JavaScript continue Statement
Note: The continue
statement is usually used inside decision-making statements such as if...else.
Example: JavaScript continue With while Loop
We can use the continue statement to skip iterations in a while
loop. For example,
let i = 0;
while (i < 5) {
i++;
if (i === 3) {
continue;
}
console.log(i);
}
Output
1 2 4 5
In the above example, the continue
statement skips the rest of the loop's body when i becomes 3.
JavaScript continue With Nested Loop
When continue
is used inside two nested loops, continue
affects only the inner loop. For example,
// nested for loops
// outer loop
for (let i = 1; i <= 3; i++) {
// inner loop
for (let j = 1; j <= 3; j++) {
if (j == 2) {
continue;
}
console.log(`i = ${i}, j = ${j}`);
}
}
Output
i = 1, j = 1 i = 1, j = 3 i = 2, j = 1 i = 2, j = 3 i = 3, j = 1 i = 3, j = 3
In the above program, the continue
statement only skips the iteration of the inner loop when j == 2
.
More on JavaScript continue Statement
In nested loops, it's possible to skip iterations of the outer loop by using a labeled continue statement.
Let's look at an example.
outerloop: for (let i = 1; i <= 3; i++) {
innerloop: for (let j = 1; j <= 3; j++) {
if (j === 2) {
continue outerloop;
}
console.log("i = " + i + ", j = " + j);
}
}
Output
i = 1, j = 1 i = 2, j = 1 i = 3, j = 1
In the above example, we have labeled our loops as:
outerloop: for (let i = 1; i <= 3; i++) {...}
innerloop: for (let j = 1; j <= 3; j++) {...}
This helps us identify the loops. Notice the use of the labeled continue
statement:
if (j === 2) {
continue outerloop;
}
This skips the current iteration of the outerloop
whenever j === 2
.
Also Read: