JavaScript Tutorial JavaScript References

JavaScript - Continue Statement



The continue statement in JavaScript let the program skip a block of codes for current iteration in a loop. Whenever the condition is fulfilled, the continue statement brings the program to the start of the loop.

If the continue statement is used in a nested loop (loop inside loop), it will skip innermost loop's code block as the condition is fulfilled.

Continue statement with While loop

In the example below, continue statement is used to skip the while loop if the value of variable j becomes 4.

var j = 0;
var txt = "";

while (j < 6){
  j++;
  if(j == 4){
    txt = txt + "This iteration is skipped.<br>";
    continue;
  }
  txt = txt + "j = " + j + "<br>";
}

The output (value of txt) after running above script will be:

j = 1
j = 2
j = 3
This iteration is skipped.
j = 5
j = 6

Continue statement with For loop

In the example below, continue statement is used to skip the for loop if the value of variable i becomes 4.

var txt = "";
for (i = 1; i <= 6; i++){
  if(i == 4){
    txt = txt + "This iteration is skipped.<br>";
    continue;
  }
  txt = txt + "i = " + i + "<br>";
}

The output (value of txt) after running above script will be:

i = 1
i = 2
i = 3
This iteration is skipped.
i = 5
i = 6

Continue statement with Nested loop

The Continue statement skip the inner loop's block of codes whenever condition is fulfilled. In below mentioned example, program skips the inner loop only when j = 100.

//Nested loop without continue statement
var txt ="# Nested loop without continue statement<br>";
for (i = 1; i <= 3; i++)
  for (j = 10; j <= 1000; j = j * 10)
    txt = txt + (i*j) + "<br>";

The output (value of txt) after running above script will be:

# Nested loop without continue statement
10
100
1000
20
200
2000
30
300
3000

//Nested loop with continue statement
var txt ="# Nested loop with continue statement<br>";
for (i = 1; i <= 3; i++){
  for (j = 10; j <= 1000; j = j * 10){
    if(j == 100)
      continue; 
    txt = txt + (i*j) + "<br>";
  }
}

The output (value of txt) after running above script will be:

# Nested loop with continue statement
10
1000
20
2000
30
3000