do/while Loops

By: Dusty Arlia
Published on November 7, 2012
Last Updated on Tuesday, July 07, 2015 at 10:51 PM
Total Updates: 6

One of JavaScript's less used loops is the do/while loop. The do/while loop is very similar to the while loop except for some syntactical differences. do/while loops start with the do keyword. This marks the beginning of the do/while loop. The while keyword marks the end of the loop and is followed by its test condition. The expression after the while keyword is followed by a semicolon to terminate the do/while loop. while loops, by comparison, do not need to be terminated with a semicolon.

do/while loops have the unique characteristic in that they always get executed at least once. Even if the expression is false, the loop will run the first time through. Here is the basic syntax of a do/while loop:

do {
} (/*expression*/);

And here is a real example of the do/while loop:

var count = 1;
do {
    document.write(count + ", ");
} while (count < 11);

In this example, the count variable is initialized to the number 1. After that, the JavaScript interpreter runs the body of the loop in between the curly braces ({}). The JavaScript interpreter will then look at the expression after the while keyword. If this expression is true, then the loop gets executed again (remember this by the saying "true, do"). Until the expression becomes false, the loop will keep running. Once the expression evaluates to false, the JavaScript program moves on to the next statement after the do/while loop.

To avoid an infinite loop, it is important that the loop body makes changes to the test condition.