Sunday 29 December 2013

Controlling Loop

Javascript(JS):
There may be situations when user tried to comes out of loop or skip the code on particular check
JavaScript provides break and continue statements to achieve this

The break Statement:
The break statement,is used to exit a loop early, come out of the enclosing curly braces.

Example:

The example will explain the use of a break statement with a while loop.
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("Enter the loop<br /> ");
while (x < 10)
{
  if (x == 5){
     break;  // breaks out of loop
  }
  x = x + 1;
  document.write( x + "<br />");
}
document.write("Exiting from loop!<br /> ");

</script>
This will produce following result:

Entering the loop
2
3
4
5
Exiting from loop!


The continue Statement:
The continue statement tells interpreter , immediately start the next iteration of
the loop and skip remaining code block.

When a continue statement is encountered, the loop 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 will explain the use of a continue statement with a while loop.
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 inside loop<br /> ");
while (x < 8)
{
  x = x + 1;
  if (x == 5){
     continue;  // skip the rest loop body
  }
  document.write( x + "<br />");
}
document.write("Exiting from loop!<br /> ");

</script>
This will produce following result:

Entering the loop
2
3
4
6
7
8
Exiting from loop!

No comments:

Post a Comment