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.

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

Professional JavaScript for Web Developers JavaScript and jQuery: The Missing Manual Murachs JavaScript and DOM Scripting