Did you find this useful?
Socialize it today.


JavaScript Break and Continue

Friday, April 13, 2012

When working with Loops in JavaScript, there may be instances where you may want to alter the normal flow of the loop by controlling it within the block of executable code. For this, we have two additional JavaScript statements: break and continue.


Break Statement

The break statement will break the for/while loop and continue executing the code that follows after the loop, if there is any code to follow. Here is an example of how to use the break statement. We will use some of the JavaScript code from the previous article.


<script type="text/javascript">
var x = 0;
for (x = 0; x <= 10; x++)
{
if (x==5)
{
break;
}
document.write(x + "<br />");
}
</script>


In this example, when x is equal to 5, the for loop will terminate. Note that the loop will terminate prior to the document.write statement.


Continue Statement

The continue statement terminates the execution of the block of statements in a for/while loop and continues execution of the loop with the next iteration. Here is an example.


<script type="text/javascript">
var x = 0;
for (x = 0; x <= 10; x++)
{
if (x==5)
{
continue;
}
document.write(x + "<br />");
}
</script>


In this example, when x is equal to 5, the code within the loop block will not be executed. The loop will continue on the next iteration. The document.write will not have been executed on that specific cycle. The results will not display the number 5 on the screen.

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

HTML CSS and JavaScript Editor Professional JavaScript for Web Developers JavaScript and jQuery: The Missing Manual