Javascript Loop Control PDF
Javascript Loop Control PDF
JavaScript provides full control to handle loops and switch statements. There may be a situation
when you need to come out of a loop without reaching at its bottom. There may also be a situation
when you want to skip a part of your code block and start the next iteration of the look.
To handle all such situations, JavaScript provides break and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of any loop
respectively.
Flow Chart
The flow chart of a break statement would look as follows −
Example
The following example illustrates the use of a break statement with a while loop. Notice how the
loop breaks out early once x reaches 5 and reaches to document.write . . statement just below
to the closing curly brace −
<html>
<body>
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
Output
We already have seen the usage of break statement inside a switch statement.
Example
This example illustrates the use of a continue statement with a while loop. Notice how the
continue statement is used to skip printing when the index held in variable x reaches 5 −
<html>
<body>
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
if (x == 5){
continue; // skill rest of the loop body
}
document.write( x + "<br />");
}
Output
Note − Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label
name. Also, there should not be any other statement in between a label name and associated
loop.
Example 1
The following example shows how to implement Label with a break statement.
<html>
<body>
<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
</body>
</html>
Output
Example 2
<html>
<body>
<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
</body>
</html>
Output