The while Statement
An alternative to the for loop is a while
loop. A while loop performs similar iterations; its
syntax, though, is different. In addition to using an index value to determine the
number of iterations,
the while loop can be brought to a close on the basis of a user event. The general format of a
while statement is shown below.
while (conditional expression) {
//statements go here...
}
Figure 5-4. General format for while statement.
As long as the conditional expression is
true, the statements between the braces are executed. The
conditional expression can be any true/false
test using the conditional and logical operators.
Although there is no required index counter or incremental expression in a
while statement, you still must provide for an initial condition - prior to the
loop - which makes the conditional expression true; otherwise, the
loop never gets executed. Plus, you need to provide a terminal condition - inside the
loop - which makes the conditional expression false; otherwise, the
loop never ends.
You can write a while loop that works like a
for loop and meets the above requirements.
function showLoop() {
var i = 1;
while (i<=5) {
alert ("This is loop #" + i);
i++;
}
}
function init() {
var showLoopBtn = document.getElementById("showLoopBtn");
showLoopBtn.onclick=showLoop;
}
window.onload=init;
<input type="button" value="Show Loop" id="showLoopBtn" />
Listing 5-4. Code to demonstrate a while loop.
Variable i is declared and initialized to 1
prior to the beginning of the loop. The loop continues as long as the value of
i is less than or equal to 5. Inside
the loop, variable i is incremented by 1
to ensure that the final condition will be reached after the loop executes 5 times.
A while loop normally is used in situations where it is not known
in advance the number of times the loop is to be iterated. In the following example, this is the
case. The user guesses a number. It could be the correct guess the first time; or if the user is
particularly dense, the number may never be guessed. A loop that iterates a fixed number of times
is not appropriate for this script.
Pick a number between 1 and 5:
Figure 5-5. Using a while loop to capture user input.
function pickEm() {
var number = Math.floor((5 - 1 + 1) * Math.random() + 1);
var guess = prompt("Pick a number between 1 and 5!", "");
while (guess != number) {
guess = prompt("Pick a number between 1 and 5 again!", "");
}
document.getElementById("output").innerText =
"Good guess! The number was " + number + ".";
}
function init() {
var pickEmBtn = document.getElementById("pickEmBtn");
pickEmBtn.onclick=pickEm;
}
window.onload=init;
Pick a number between 1 and 5:
<input type="button" value="Guess a number" id="pickEmBtn"/>
<p><span id="output" style="color:red; font-weight:bold"></span></p>
Listing 5-5. Code to use a while loop to capture user input.
The button calls the pickEm() function for choosing the
correct number and ending the loop. First, a target number is chosen by the script by generating
a random number between 1 and 5. This value is stored in variable number.
Then, variable guess is initialized to "".
This assignment ensures that the condition test (guess != number) is
true the first time the loop is entered and that the prompt box gets
displayed. When a number is entered into the prompt box, it is assigned to variable
guess and control returns to the top of the loop where the condition test
is made again. As long as a value other than a match to number is
entered in the prompt box, the condition test is true and the loop
repeats. Only after entering a matching number does the test become
false and the loop ends.
Note that the input and test values are treated as strings. A prompt box supplies string
values even when numerals are entered into the box; and, although the random number is a numeric
value, JavaScript converts it to a string for proper comparison in the test (guess != number). In this case, it does not matter that both values
are strings. The script is looking for a matching character, not a matching numeric quantity.
The script can be simplified by including the prompt method in the
condition test. In the following rewrite, the value return by the prompt box is tested against
the expected value. There is no need, even, for statements inside the while
loop.
function pickEm() {
var number = Math.floor((5 - 1 + 1) * Math.random() + 1);
while (prompt("Pick a number between 1 and 5:", "") != number) {
}
document.getElementById("output").innerText =
"Good guess! The number was " + number + ".";
}
Listing 5-6. Alternate code to use a while loop to
capture user input.