The continue statement in Javascript is used to break the iteration of the loop and follow with the next iteration. The break in the iteration is possible only when the specified condition going to occur.
The major difference between the continue and break statement is that the break statement breaks out of the loop completely while continue is used to break one statement and iterate to the next statement.
How does the continue statement work for different loops?
- In a For loop, iteration goes to an updated expression which means the increment expression is first updated.
- In a While loop, it again executes the condition.
Syntax:
continue;
Example 1: In this example, we will use the continue statement in the for loop.
Javascript
for (let i = 0; i < 11; i++) { if (i % 2 == 0) continue ; console.log(i); } |
Output: In the above example, the first increment condition is evaluated and then the condition is checked for the next iteration.
1
3
5
7
9
Example 2: In this example, we will use the continue statement in the while loop.
Javascript
let i = 0; while (i < 11) { i++; if (i % 2 == 0) continue ; console.log(i); } |
Output: In the above example, the first condition is checked, and if the condition is true then the while loop is again executed.
1
3
5
7
9
11