HTML and CSS Reference
This screenshot shows the out-
put in the console from the
while loop. Incrementing by
two each time through the loop
means only five iterations.
You would normally use a while loop when you weren't sure how many
iterations (trips through the loop) were required. Whereas the for loop
always counts from something to something, a while loop does as many
or as few iterations as required. For instance, if you had a collection of
10,000 numbers and wanted to find the first one that was even, you
would use a while loop because you would expect to find an even num-
ber in the first few you looked at.
There's a variation on the while loop called the do...while loop. As you
can see in the next diagram, it's similar to the while loop; the main differ-
ence is that the test to see whether the loop should continue is at the end.
var i = 0;
console.log('Loop ' + i);
i += 2;
} while (i < 10)
Loop while this
expression is true.
The previous do...while loop
produces exactly the same
output as the earlier while
loop. For a large number of
iterations, this will always be
true. The main difference
comes when the while loop
may not be executed at all.