The 'while …
' statement repeats a statement or block based on a condition. Its syntax is:
while ( condition )
statement or block
If the condition is met, one repetition occurs. After that, the condition is checked again to see if there should be another repetition, and so on. If the condition is never true
, then no repetitions at all occur. Care has to be taken that the condition eventually stops the cycle or the loop will go on forever. Some examples:
var num = 134 - 1; // example 1. Find the biggest factor of 134.
var finished = false;
while ( finished == false )
{
if ( 134 % num == 0 )
{
document.write('The biggest factor of 134 is ' + num);
finished = true;
}
num--;
}
num = 1; // example 2. Display all the numbers (never ends).
while (true)
{
document.write(++num + ' ');
}