Javascript TUTORIAL


Javascript Break and Continue statements

The break break and continue are used inside the for and/or while loop to alter the normal flow of sequence of the loop.

Break statements

The break statement will break the loop. If there are any statements beyond the loop, it will continue executing the code that follows after the loop.

Break Statement Example


<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example While loop
********************************************************
*/
var i=0;
while (i<=10)
{
if (i==3)
{
break;
}
square_i = i*i ;
document.write("The square of " +i +" is " +square_i );
document.write("<br />");
i=i+1;
}
//-->
</script>
</body>
</html>



The example defines the while loop that starts with i=0. The loop will continue to run by incrementing i. When i becomes 3 the loop will break. It will therefore produce the result as follows.


The square of 0 is 0
The square of 1 is 1
The square of 2 is 4

Continue statements

The continue command will break the current loop and continue with the next value.

Continue Statement Example


<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Example Continue statement
********************************************************
*/
var i=0;
while (i<=10)
{
if (i==3)
{
i = i +2; continue;
}
square_i = i*i ;
document.write("The square of " +i +" is " +square_i );
document.write("<br />");
i=i+1;
}
//-->
</script>
</body>
</html>



The example defines the while loop that starts with i=0. The loop will continue to run by incrementing i. When i becomes 3 the loop will not execute. We also note that we assigned i = i + 2. So the loop continues to run after assigning the value of i to 5. It will therefore produce the result as follows.


The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of5 is 25
The square of 6 is 36
The square of 7 is 49
The square of 8 is 64
The square of 9 is 81
The square of 10 is 100