Do While Once in a While

The other day, a programmer I follow on Twitter was pleased because he had found a good use for a do/while loop.

When a programmer gets excited by a loop construct, you know something is wrong. The truth is that do/while is underutilized, not just in JavaScript but in all C-based languages.

The rule of thumb is that you should use always use a do/while loop when the body of the loop must execute at least once. Use a while loop when the body of the loop may never execute.

Maybe it’s true that a while loop is indicated more often than a do/while loop, but I’ve often seen programmers do a little jury-rigging to patch up the while loop to do their bidding when a do/while would have meant less typing and have made more sense.

Why? Well, programmers get into habits. If you get to know while very well, you may be shy about using do/while.

But I think there’s some clumsiness inherent in do/while that also plays a part in its unpopularity. It’s a result of JavaScript getting its syntax genes from C rather than the Wirth family of languages. Pascal and the others (Modula-2 and Oberon) used repeat/until

do {
  a = a + 1;
} while (a!==10);

  a := a + 1
until a = 10;

I think repeat/until is superior to do/while for these reasons:

  • In JavaScript, the reuse of the identifier “while” is awkward. When you see it, you tend to expect the loop body to come after it. See how it just sits there AFTER the close brace? Like a teenage boy avoiding a girl at a middle school dance.
  • do/while‘s ending condition is the same as while‘s starting condition. Pascal’s until condition is logically negated, which I think is more natural at the end of a loop. Do something over and over UNTIL something is true, rather than do something over and over WHILE something is true. REPEAT UNTIL i hits 5, rather than DO WHILE i is less than 5. A possible solution would be to allow do/until as well as do/while. This would allow for backward compatibility. Someone remind me I said that the next time I invent my own computer language.

In short, the do/while construct just doesn’t sit quite right in C, encouraging the overuse of the while loop, which sits just fine. In any case, repeat/until seems to get more use in Pascal than do/while gets in C.

Don’t forget do/while is there, waiting for you to be excited to use it. It’s the right choice when you must execute the body at least once.