JavaScript Loop Control
JavaScript provides you full control to handle your loops and switch statement. 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 want to start 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.
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.Example:
This 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 closing curly brace:<script type="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>
|
The continue Statement:
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip remaining code block.When a continue statement is encountered, program flow will move to the loop check expression immediately and if condition remain true then it start next iteration otherwise control comes out of the loop.
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:<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>
|
No comments:
Post a Comment