Javascript’s little-known do-while loop

Many Javascript programmers are familiar with the while loop, which executes iterates until a given condition evaluates to false. It’s a pretty handy construct and can provide the fastest loops in the Javascript world (if used properly). However, there is a drawback. If the given condition evaluates to false immediately, the while loop will not run even once. This is because the while loop’s condition is evaluated before executing the code within the loop. “Oh well,” you say, “if that’s the case, then too bad, right?” Wrong.

Introducing: the do-while loop

The do-while loop is a lesser-known cousin of the while loop that few Javascript programmers know about. Unlike the while loop, it executes its statement exactly once before evaluating its condition. The do-while loop looks like this:

do {
} while (condition);

Because the statement of a do-while loop is executed once before the condition is evaluated, you can do interesting stuff like this:

do {
// statement
} while (false);

If we were using an ordinary while loop, the above statement would fail. However, because the statement of a do-while loop is executed before the condition is evaluated, the above code runs once and then fails.

Too long; didn’t read

Functionally, the do-while loop is the equivalent of this while loop:

while(true) {
// statement

if(condition == false) {

Leave a Reply

Your email address will not be published. Required fields are marked *