HTML and CSS Reference
In-Depth Information
The body of the loop just prints out a message that includes the value of count each time
through the loop.
CAUTION
As you can see, the
for
statement is self-contained. The
count
variable is declared, tested, and incremented within that state-
ment. You shouldn't modify the value of
count
within the body of
your loop unless you're absolutely sure of what you're doing.
while Loops
The basic structure of a
while
loop looks like this:
var color = 'blue';
while (color == 'blue') {
document.write(“Color is still blue.”);
if (Math.random() > 0.5) {
color = 'not blue';
}
}
The
while
loop uses only a condition. The programmer is responsible for creating the
condition that will eventually causes the loop to terminate somewhere inside the body of
the loop. It might help you to think of a
while
loop as an
if
statement that's executed
repeatedly until a condition is satisfied. As long as the
while
expression is true, the state-
ments inside the braces following the
while
loop continue to run forever—or at least
until you close your web browser.
In the preceding example, I declare a variable,
color
, and set its value to
“blue”
. The
while
loop will execute until it is no longer true that
color
is set to
“blue”
. Inside
the loop, I print a message indicating that the color is still blue, and then I use an
if
statement that may set the
color
variable to a different value. The condition in the
if
statement uses
Math.random()
, which returns a value between
0
and
1
. In this case,
if it's greater than 0.5, I switch the value so that the loop terminates.
If you prefer, you can write
while
loops with the condition at the end, which ensures that
they always run once. These are called
do ... while
loops, and look like this:
var color = “blue”;
do {
// some stuff
14
}
while (color != “blue”);
Even though the test in the loop will not pass, it will still run once because the condition
is checked after the first time the body of the loop runs.