Section 6.7. dowhile


6.7. do/while

The do/while loop is much like a while loop, except that the loop expression is tested at the bottom of the loop rather than at the top. This means that the body of the loop is always executed at least once. The syntax is:

 do     statement while (expression); 

The do/while loop is less commonly used than its while cousin. This is because, in practice, it is somewhat uncommon to encounter a situation in which you are always sure that you want a loop to execute at least once. Here's an example of a do/while loop:

 function printArray(a) {     if (a.length == 0)         document.write("Empty Array");     else {         var i = 0;         do {           document.write(a[i] + "<br>");         } while (++i < a.length);     } } 

There are a couple of syntactic differences between the do/while loop and the ordinary while loop. First, the do loop requires both the do keyword (to mark the beginning of the loop) and the while keyword (to mark the end and introduce the loop condition). Also, unlike the while loop, the do loop is terminated with a semicolon. This is because the do loop ends with the loop condition, rather than simply with a curly brace that marks the end of the loop body.




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net