Java Reference
In-Depth Information
alert("Test Variable is " + testVariable);
testVariable++;
if (testVariable = 10) {
alert("The last loop");
}
}
See if you can spot the deliberate mistake that leads to an infinite loop—yes, it's the
if
if statement that will cause this code to go on forever. Instead of using
==
as the comparison
operator in the condition of the
if
statement, you put
=
, so
testVariable
is set to
10
again in
each loop, despite the line
testVariable++
. This means that at the start of each loop, the test
condition always evaluates to
true
, because 10 is less than or equal to 10. Put the extra
=
in to make
if (testVariable == 10)
, and everything is fine.
the do . . . while loop
With the
while
loop, you saw that the code inside the loop only executes if the condition is
true
;
if it's
false
, the code never executes, and execution instead moves to the first line after the
while
loop. However, there may be times when you want the code in the
while
loop to execute at least
once, regardless of whether the condition in the
while
statement evaluates to
true
. It might even be
that some code inside the
while
loop needs to be executed before you can test the
while
statement's
condition. It's situations like this for which the
do . . . while
loop is ideal.
Look at an example in which you want to get the user's age via a prompt box. You want to show the
prompt box but also make sure that what the user has entered is a number:
var userAge;
do {
userAge = prompt("Please enter your age","")
} while (isNaN(userAge) == true);
The code line within the loop:
userAge = prompt("Please enter your age","")
will be executed regardless of the
while
statement's condition. This is because the condition is not
checked
until
one loop has been executed. If the condition is
true
, the code is looped through again.
If it's
false
, looping stops.
Note that within the
while
statement's condition, you are using the
isNaN()
function that you saw
in Chapter 2. This checks whether the
userAge
variable's value is NaN (Not a Number). If it is not
a number, the condition returns a value of
true
; otherwise, it returns
false
. As you can see from
the example, it enables you to test the user input to ensure the right data has been entered. The user
might lie about his age, but at least you know he entered a number!
The
do . . . while
loop is fairly rare; there's not much you can't do without it, so it's best avoided
unless really necessary.