Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
while LoopsAnother keyword for loops in JavaScript is while. Unlike for loops, while loops don’t necessarily use a variable to count. Instead, they execute as long as a condition is true. In fact, if the condition starts out as false, the statements won’t execute at all.
The while statement includes the condition in parentheses, and it is followed by a block of statements within braces, just like a for loop. Here is a simple while loop:
while (total < 10) {
n++;
total += values[n];
}
This loop uses a counter, n, to iterate through the values array. Rather than stopping at a certain count, however, it stops when the total of the values reaches 10.
You might have noticed that you could have done the same thing with a for loop: