Continue statement in javaScript; Through this tutorial, i am going to explain you everything about continue statement in javaScript and it’s usage with example.
JavaScript Continue Statement
- JavaScript
continue
statement - Syntax of JavaScript
continue
statement - Example 1:
continue
statement with for loop - Example 2:
continue
statement with while loop - Example 3:
continue
statement with do while loop - Example 4: Using
continue
statement to exit nested loop
JavaScript continue
statement
The javascript continue
statement skipped the execution in programs or scripts.
Syntax of JavaScript continue
statement
continue;
Example 1: continue
statement with for loop
See the following example of continue
statement with for loop:
<script> var i = 1; for (i; i <= 10; i++) { if (i % 5 == 0) { continue; } document.write(i + "<br>") } </script>
The output of the script shown below:
1 2 3 4 6 7 8 9
The explanation of above program; as shown below:
- To define a variable
i
and initialize it value to 1. - Then, add test condition.
- Increase the value of
i
by 1 in each iteration of the loop. - Use if statement with continue statement to skipped iteration according to given condition.
- At the print the value of
i
.
Example 2: continue
statement with while loop
Use the following example of continue
statement with while loop:
<script> var i = 1; while(i <= 10) { if (i % 5 == 0) { continue; } document.write(i + "<br>") } </script>
The output of the script shown below:
1 2 3 4 6 7 8 9
Example 3: continue
statement with do while loop
Use the following example of continue
statement with do-while loop:
<script> var i = 1; do { i++ if (i % 5 == 0) { continue; } document.write(i + "<br>") } while(i <= 10) </script>
The output of the script shown below:
1 2 3 4 6 7 8 9 11
Example 4: Using continue
statement to exit nested loop
You use the continue
statement to skipped a label statement and transfer control to the next statement following the skipped statement.
The syntax is as follows:
continue label;
The continue
statement is typically used to exit the nested loop. See the following example.
<script> // continue with a label outer: for (let i = 1; i <= 3; i++) { for (let j = 1; j <= 3; j++) { if ((i == 2) && (j == 2)) { document.write("<br> continue to outer" + "<br>") continue outer; } document.write("[i:" + i + ",j:" + j + "]") } } </script>
The output of the script shown below:
[i:1,j:1][i:1,j:2][i:1,j:3][i:2,j:1]
continue to outer
[i:3,j:1][i:3,j:2][i:3,j:3]
Here,
- The
for
loops increment the variablei
andj
from 1 to 3. - And inside the body of the innermost loop, we check if both
i
andj
are equal to 2. If so, we output a message to the web page and jump back to theouter
label. Otherwise, we output the values ofi
andj
in each iteration.
Conclusion
In this tutorial, you have learned what is continue statement and how to use the JavaScript continue
statement to control the code execution of for loop and nested loop.