Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Using do...while Loops

JavaScript 1.2 introduced a third type of loop: the do...while loop. This type of loop is similar to an ordinary while loop, with one difference: The condition is tested at the end of the loop rather than the beginning. Here is a typical do...while loop:

do {
n++;
total += values[n];
}
while (total < 10);

As you've probably noticed, this is basically an upside-down version of the while example above. There is one difference: With the do loop, the condition is tested at the end of the loop. This means that the statements in the loop will always be executed at least once, even if the condition is never true.

Share ThisShare This

Informit Network