JAVA SCRIPT DAY 8 (Loop Control, break Statement,continue Statement)

DAY - 8

JavaScript - Loop Control

Ø  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 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 loop.
Ø  To handle all such situations, JavaScript provides break and continuestatements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively.

The break Statement

Ø  The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces.

Ø  Flow Chart

Ø  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>

<scripttype="text/javascript">
<!--
var x =1;
document.write("Entering the loop<br /> ");

while(x <20)
{
if(x ==5){
break; // breaks out of loop completely
}
            x = x +1;
document.write( x+"<br />");
}

document.write("Exiting the loop!<br /> ");
//-->
</script>

<p>Set the variable to different value and then try...</p>
</body>
</html>

Output

Entering the loop
2
3
4
5
Exiting the loop!

 

The continue Statement

Ø  The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block.
Ø  When a continuestatement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.
Ø  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 /> ");
while(x <10)
{
               x = x +1;
if(x ==5){
continue; // skip rest of the loop body
}
document.write( x+"<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
2
3
4
6
7
8
9
10

No comments:

Post a Comment

Give your valuable feedback

Topic :Software & Types, Subject: Computer Fundamental Notes for CSJM University Kanpur(for different courses like BBA, BCA, etc..)

Software Software refers to the programs, data, and instructions that enable a computer or other digital device to perform specific tasks or...