Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

Using Do/While Loops

Sometimes you'll need to have a loop in your code that loops around a number of times, but there's no way of knowing how many times you'll want to loop. That's when you'll want to use a do/while loop: you want to do something, while some value is true. Script 3.5 continually asks a user to enter a name, and it won't give up until it gets a response.

03fig12.jpg

Script 3.5 This loop will continue to bug the user until they finally enter something.

To use a do/while loop

  1. do { This line starts the do block of code. One of the things you have to remember about this type of loop is that the code inside the do block will always be executed at least once.
  2. ans = prompt("Tell me your name","") This is a standard prompt() method, as was covered in Chapter 2. In this case, it asks for the user's name, as shown in Figure 3.8 .
    03fig13.gif

    Figure 3.8 Ask users for their name until they give in.

  3. } The closing brace signals the end of the do block.
  4. while (!ans) The while check will cause the do block of code to repeat until the check evaluates to false. In this case, we're checking to see if ans has any value. If it doesn't (e.g., the user hit Cancel, or the close box, or OK without entering any data), control will be passed back to the top of the do block and the whole process starts again. Eventually, the user will get so tired of being asked the same question that they'll finally give up and enter something.
  5. alert("Hello, " + ans) At which point, they'll end up here, with a friendly "Hello" to welcome them to your site, as shown in Figure 3.9 .
    03fig14.gif

    Figure 3.9 When a name is entered, welcome the user to your site.

  • + Share This
  • 🔖 Save To Your Account