Using while Loops
Another 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:
for (n=0;total < 10; n++) {
total += values[n];
}
As a matter of fact, the for loop is nothing more than a special kind of while loop that handles an initialization and an increment for you. You can generally use while for any loop. However, it's best to choose whichever type of loop makes the most sense for the job, or that takes the least amount of typing.
|