HTML and CSS Reference
In-Depth Information
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.
Starting state
var i = 0;
do {
console.log('Loop ' + i);
i += 2;
} while (i < 10)
statement block
to repeat
Increment the
variable after
every loop.
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.
 
Search WWH ::




Custom Search