Break and continue in Javascript.

Using break and continue keyword in loop statements

The endless loop

  • You can create endless loop, which runs forever, using a for Statement, using a while statement or a do/while statement.
    // Here is a endless for loop that runs forever.
    for (;;) {
        statement;
    }
    // Here is a endless while loop that runs forever.
    while (true) {
        statement;
    }
    // Here is a endless do-while loop that runs forever.
    do {
        statement;
    } while (true)
  • In these loops you have to use at least one break keyword to end the loop.
  • You can also use the continue keyword in any loop. A continue keyword cause a jump to an new expression evaluation .
  • The break keyword can be used in any loop and cause a jump out of the loop.
    Example of a endless for loop with break keyword and continue keyword:
    <script type="text/javascript">
       var count=0, max=5;
      for (;;) {            // A for loop that doesn't end
        if (count < max) {  // test
          count++;          // increment
          if (count==2) {
            continue;
          }
          // All counts are listed except number 2
          document.write("Counter : " + count + "<br>");
        }
        else
          // You must have at least one break
          //  in a endless loop; like this
          break;
      }
    </script>

Using labels

  • Any loop can exist in any loop that can exist in any loop and so on. In those cases, the break keyword and continue keyword only works in the loop it exists.
  • JavaScript allows the break keyword and the continue keyword to be followed by the name of a label.
    break labelName;
    continue labelName;
  • Any statement may be labeled by preceding it with an identifier name and a colon:
    identifier: statement;
    Example using break keyword and continue keyword with use of labels:
    <script type="text/javascript">
      var x = 0;
      outerloop:
        for(;;) {
        x++;
        innerloop:
        for(var y = 0; y < 10; y++) {
          if (x == 9 ) break outerloop;  // quit outer loop
          if (y > 3) break;             // Quit the innermost loop
          if (x == 2) break innerloop;  // Do the same thing
          if (x == 4) continue outerloop;  // new outer loop test
          if ((x >= 7) && (x < 9)) continue;  // new inner loop test
          document.write("x = " + x + " y = " + y + "<br>");
        }
      }
      document.write("At end x = " + x + " y = " + y + "<br>");
    </script>

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.