Java Reference
In-Depth Information
Something to watch out for is the infi nite loop — a loop that will never end. Suppose you forgot to include
the loopCounter++; line in the code. Leaving this line out would mean that loopCounter will remain
at 0, so the condition (loopCounter < 3) will always be true, and the loop will continue until the user
gets bored and cross, and shuts down her browser. However, it is an easy mistake to make and one
JavaScript won't warn you about.
It's not just missing lines that can cause infi nite loops but also mistakes inside the loop's code. For
example:
var testVariable = 0;
while (testVariable <= 10)
{
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 infi nite loop — yes, it's the 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, since 10 is less than or
equal to 10. Put the extra = in to make if (testVariable == 10), and everything is fi ne.
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 fi rst 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 condi-
tion. 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.
Search WWH ::




Custom Search