while Loops

A while loop is similar to a for loop in that it enables repeated execution of a block of statements. However, a while loop does not have a built-in counter variable or update expression. To control repetitive execution of a statement or block of statements with a more complex rule than simply "run this code n times", use a while loop.

Using while Loops

The following example demonstrates the while statement:

var x = 1;
while (x < 100) {
   print(x);
   x *= 2;
}

The output of this program is:

1
2
4
8
16
32
64

Note

Because while loops do not have explicit built-in counter variables, they are more vulnerable to infinite looping than the other types of loops. Moreover, because it is not necessarily easy to discover where or when the loop condition is updated, it is easy to write a while loop in which the condition never gets updated. For this reason, you should be careful when you design while loops.

As noted above, there is a do...while loop in JScript similar to the while loop. A do...while loop is guaranteed to always execute at least once since the condition is tested at the end of the loop rather than at the start. For example, the loop above can be rewritten as:

var x = 1;
do {
   print(x);
   x *= 2;
}
while (x < 100)

This output of this program is identical the output shown above.

See Also

Reference

while Statement

do...while Statement

Other Resources

Loops in JScript

JScript Conditional Structures

JScript Reference