Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

Using do...while Loops

JavaScript, like many other programming languages, includes a third type of loop: the do...while loop. This type of loop is similar to an ordinary while loop, with one difference: The condition is tested at the end of the loop rather than the beginning. Here is a typical do...while loop:

do {
    n++;
    total += values[n];
}
while (total < 10);

As you’ve probably noticed, this is basically an upside-down version of the previous while example. There is one difference: With the do loop, the condition is tested at the end of the loop. This means that the statements in the loop will always be executed at least once, even if the condition is never true.


Note

As with the for and while loops, the do loop can include a single statement without braces or a number of statements enclosed in braces.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial