Creating do while LoopsThere's another form of the while loop available: the do...while loop. This loop is much like the while loop, except that it checks the loop condition at the end, after the code in the loop has been executed, not at the beginning. Here's what this loop looks like in outline: do { code } while (condition) Actually, there's a big difference between the while and do...while loops in programmatic terms: The code in a do...while loop is always executed at least once, although that's not true of a while loop. Take a look at this example: var number = 25 do { document.writeln("The reciprocal of " + number + " is " + 1/number + "<BR>") --number } while (number > 0) Here I'm displaying a sequence of reciprocal values, from 1/25 up to 1/1 , using a do...while loop. However, this would be a problem if number were initialized to because the first reciprocal that the code would attempt to calculate is 1/0 : var number = 0 do { document.writeln("The reciprocal of " + number + " is " + 1/number + "<BR>") --number } while (number > 0) A better choice is to use the while loop here: It checks the value in number first and won't attempt to calculate a reciprocal if that value equals : var number = 25 while (number > 0) { document.writeln("The reciprocal of " + number + " is " + 1/number + "<BR>") --number } Both forms of the while loop have their places, however. For example, if you need to execute the body of the loop before testing to see if the loop should continue, use the do...while loop. |