The JavaScript continue statement skips the current iteration immediately and continues to the next iteration of the loop. Unlike the break statement, the continue statement does not exit the loop. It only skips the current iteration.
Table of Contents
Syntax
1 2 3 | continue [label]; |
Where the label
is optional. We use it when we have a nested loop to correctly identify the loop
Continue with a while loop
In the following while loop example, we use the continue statement to skip the iteration if the value of i
is 3. Because of this, the value 3 is not printed on the console. The loop does not stop but continues to the next iteration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | var i = 0; while (i < 5) { i++; if (i === 3) { continue; } console.log(i); } ** Console ** 1 2 4 5 |
Continue with a for loop
In this for loop example also skips the rest of the loop, when the value of i
is 3.
1 2 3 4 5 6 7 8 9 10 11 12 13 | for (let i = 0; i < 5; i++) { if (i == 3) continue; console.log(i); } ** Console ** 0 1 2 4 5 |
Continue statement in nested loops
In the following nested for loop example, the continue statement skips the inner loop, but not the outer loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | for (let i = 0; i < 4; i++) { for (let j = 0; j < 4; j++) { if (j == 2) continue; console.log(i + " " + j); } } *** Console *** 0 0 0 1 0 3 1 0 1 1 1 3 2 0 2 1 2 3 3 0 3 1 3 3 |
To exit from the outer loop, we make use of the labeled statement
In the following examples, we label the outer loop as outerloop
and inner loop as innerloop
. The continue statement now skips the outer loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | outerloop: for (let i = 0; i < 4; i++) { innerloop: for (let j = 0; j < 4; j++) { if (j == 2) continue outerloop; console.log(i + " " + j); } } *** Console *** 0 0 0 1 1 0 1 1 2 0 2 1 3 0 3 1 |