Web Development Tutorials




  
  

The do...while Statement

A do...while loop is similar to a while loop except that you are guaranteed that the statements in the loop will be executed at least one time. The condition test for ending the loop appears as the last statement in the loop; so, processing occurs at least one time before the condition test is evaluated. Also, it is not necessary to ensure a true condition for initiating the loop. The general format for a do...while loop is shown below.

do {
   //statements go here...
}
while (conditional expression)

Figure 5-6. General format for do...while statement.

This construct is more appropriate for the number-guessing application shown previously since the prompt box needs to display at least one time (the first time). Also, it is not necessary to initialize the Guess variable since it is not tested until after it takes on its first value.

Pick a number between 1 and 5:

Figure 5-7. Using a do...while loop to capture user input.

function pickEm() {
  var number = Math.floor((5 - 1 + 1) * Math.random() + 1);
  do {
    var guess = prompt("Pick a number between 1 and 5:", "");
  }
  while (guess != number) 
  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" id="pickEmBtn" />
<p><span id="output" style="color:red; font-weight:bold"></span></p>

Listing 5-7. Code to use a do...while loop to capture user input.

This script also 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.

function pickEm() {
  var number = Math.floor((5 - 1 + 1) * Math.random() + 1);

  do {
    // do nothing until conditional statement is satisfied.
  }
  while (prompt("Pick a number between 1 and 5:", "") != number);

  document.getElementById("output").innerText = 
    "Good guess! The number was " + number + ".";
}

Listing 5-8. Alternate code to use a do...while loop to capture user input.


TOP | NEXT: Break/Continue Statements