Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

The JavaScript Language 485

17


while Loops The basic structure of a while loop looks like this :


var color = 'blue';
while (color == 'blue') {
console.log("Color is still blue.");
if (Math.random() > 0.5) {
color = 'not blue';
}
}


One thing you may notice when you’re entering code in the
Console is that multiline statements will return an error if you
enter part of the statement and press Return. To enter multiline
statements yourself, you can either paste them into the Console
instead of typing them, or you can press Shift-Return at the end
of the lines to indicate that they are part of a multiline block.
When you press the Return key at the end, all the lines will be
evaluated together.

TIP

The while loop uses only a condition. The programmer is responsible for creating the
condition that will eventually cause 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(), another method of the Math object that 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
}
while (color != "blue");

Free download pdf