Break and Continue

While we are talking about loops, JavaScript has two powerful statements that also be used, break and continue. You will gain an understanding of each one does in the following examples.

Example
var i = 0;
for (i = 0;i <= 5;i++)
{
    if (i==2)
    {
        break;
    }
    document.write(i);
    document.write("<br />");
}
document.write( "End of for loop" );
Result

0
1
End of for loop

Once the var i reaches 2 in the for loop, it meets the conditional statement i == 2, which is then executed. The statement executed is break;. Once break is executed it actually breaks us out of the for loop, which is why when i equals 2, we exit the for loop and execute document.write( “End of for loop”); instead of ending the for loop when i equals 5.

Example
var i = 0;
for (i = 0;i <= 5;i++)
{
    if (i==2)
    {
    continue;
    }
    document.write(i);
    document.write("<br />");
}
document.write( "End of for loop" );
Result

0
1
3
4
5
End of for loop

It seems pretty obvious that continue different than the break. Notice how the only result not printed is 2. The continue; basically says let’s skip out of this particular instance of the loop and move onto the next one. So when we are running through the instance where i becomes equal to 2, we meet the conditional statement if( i == 2) where it is true. Then, we execute the continue, which stops us from executing the following statements in the loop. We then run through the next instance of the loop where i equals 3. Since we don’t meet the conditional statement this time, we will write the following statements and will never enter into conditional if(i == 2).

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.