HoloGuides :: Know Everything ! Programming
JavaScript . while



  loop while
  while() {...}
  Netscape Reference
 
  Description

while looping is used to make sure the statements within the loop are executed only if the condition is true.
The condition is tested before the statements are executed.
In contrary to the do-while combination where the first check is done after the first loop is already executed. 

  Syntax

while(condition)
 {
 statements;
// this is executed if condition evaluates to true
 }

  Syntax example

myVariable=0; // make sure you start with an initialized myVariable

while (myVariable < 10) // use the proper comparision operator (see below)
{
statements if condition is true;
// this is executed as long as myVariable is less than 10
myVariable = myVariable + 2; // myVariable should be incremented here to avoid endless loops
}

comparison operators
== is equal
!= is different
< is less than
<= is less than or equal
>= is equal or greater than
> is greater than

 

  Working sample

 

execute some statements 3 times

lastNumber = 4;
myCounter = 1; // important : initialize your variables
while
(myCounter < lastNumber') // important : use the == operator to compare, not the = to assign
{
myCounter = myCounter++; // this increments the myCounter variable by 1 (shortcut for myC = myC + 1)
alert(myCounter);
}

 

  A B C