while loop

A while loop repeats a short comparison until it is no longer true. A while loop does not create a variable.
You have to remember to create it, assign a value to it then insert it into the loop.


var MyVariable = 1;
while (MyVariabl e< 10) {
     document.write("This is a while loop in action.");
     MyVariable++;
}

The script starts with the declaration of the variable MyVariable which is assigned a value of 1.
Then the loop begins with the while keyword followed by the condition MyVariable < 10 so the loop will execute if MyVariable < 10.

Notice the MyVariable++;. Without it the loop will repeat indefinitely since the variable MyVariable will stay with the value of 1.

As in the case of for loops you can nest a while loop within another loop, for loop, if/else statement etc.

Leave a Reply