break and continue statements

The break and continue statements allow you to stop what a loop is doing.


for (MyVariable = 1; MyVariable < 10; MyVariable++) {
     if (MyVariable = =5) {
          document.write("MyVariable is 5 now. I stopped!");
          break;
     }
     else {
          document.write("This is part of the loop.");
     }
}

At the first glance the loop should write 9 times the sentence “This is part of the loop.” but then a condition appears.
When MyVariable has a value of 5 the script will write the sentence “MyVariable is 5 now.
I stopped!” then the keyword break will stop the loop.

In contrast, the continue statement will stop the loop when the variable is 5 but then will continue where it left off.


for (MyVariable = 1; MyVariable < 10; MyVariable++) {
     if (MyVariable == 5) {
     continue;
     }
     document.write(MyVariable + ". This is part of the loop.");
}

The sentence “This is part of the loop.” will be written 8 times only because nothing will be written on the page when MyVariable is 5.

Leave a Reply