- Detecting Browser Plug-ins
- Around and Around with Loops
- Writing with Loops
- Using For/In Loops
- Using Do/While Loops
- Checking if Java Is Enabled
- Functions
- Using Multi-level Conditionals
- Working with Functions That Return Values
- Handling Errors
- Putting More than One Script on a Page
- Scrolling Status Bars
- Status Bar Messages
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.

Script 3.5 This loop will continue to bug the user until they finally enter something.
To use a do/while loop
- 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.
-
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
.
Figure 3.8 Ask users for their name until they give in.
- } The closing brace signals the end of the do block.
- 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.
-
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
.
Figure 3.9 When a name is entered, welcome the user to your site.