Thursday, June 21, 2012

Java Script Tutorial 12 : JavaScript While Loop


The while Loop :
The while loop loops through a block of code while a specified condition is true. Syntax of while loop is as follow :


while (variable<endvalue)
  {
       code to be executed
  }


For example


while (i<3)
  {
  y=y + "The number is " + i + "<br />";
  i++;
  }


The above while loop will run when value of i less then 3, and it will stop working when it is exceed or equal to 3.


The do  .. while Loop :
The do .. while loop is a variant of the while loop. This loop will execute the block of code once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. Syntax of do .. while loop is as follow :


do
  {
       code to be executed
  }
while (variable<endvalue);


For example


do
  {
  y=y + "The number is " + i + "<br />";
  i++;
  }
while (i<3);


The above loop will run once before checking condition, and then it will check condition every time, and run only if condition met.

No comments:

Post a Comment