Continue Statement in JavaScript

The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

The continue statement (with or without a label reference) can only be used to skip one loop iteration.

The difference between continue and the break statement, is instead of “jumping out” of a loop, the continue statement “jumps over” one iteration in the loop.

However, when the continue statement is executed, it behaves differently for different types of loops:

  • In a while loop, the condition is tested, and if it is true, the loop is executed again
  • In a for loop, the increment expression (e.g. i++) is first evaluated, and then the condition is tested to find out if another iteration should be done

The continue statement can also be used with an optional label reference.

Example

The example below illustrates the use of a continue statement with a while loop. Notice how the continue statement is used to skip printing when the index held in variable x reaches 5

<html>
   <body>

      <h1>JavaScript Continue Statement</h1>

      <script type="text/javascript">
            var x = 1;
            document.write("Loop Starts here.....<br /> ");
         
            while (x < 8)
            {
               x = x + 1;
               
               if (x == 5){
                  continue; /*skip rest of the loop body and take control to start of while condition*/
               }
               document.write( x + "<br />");
            }
         
            document.write("Loop terminates!<br /> ");
      </script>
   </body>
   
   <br/><br/>
   <p>Powered by easycode.onewebapp.com</p>
</html>

 

Output

JavaScript - Continue Statement