A rollercoaster shot against the sky, photographed in black and white

Less common than the standard for loop, do and do… while loops have particular use-cases that make them invaluable in JavaScript development.

Short of escaping via break or playing with the iterator value, a for loop will always execute the number of times you specify: if you tell a for loop to iterate n times, it will always do so. On the other hand, do… while and while loops only execute as many times as needed until a particular condition is met.

do-while

do…while is used when you need something done at least once, but don’t know the number of times the process may need to be repeated. It takes the following structure:

do {
    statements;
} while (condition);

do… while loops will always execute at least once (unlike while loops, which may never run at all). In other words, a do… while will always execute the loop, then check the condition.

A good example might be using a random value to increase a variable, up to a particular maximum value. I’m using just this approach in an upcoming simple HML5 game built in .

An SVG circle divided into random sectors

In the game, I need to divide a circle into sectors, like a pie chart. However, I don’t want the sectors to be even, or equal: I just need them to be at least a minimum angle, and no larger than a maximum angle. However large or small the sectors are, I only need enough of them to get all the way around the 360 degrees of the circle. In other words, I won’t know how many times the loop needs to run before I start it, but I know it will run at least once, making it a perfect application for the do… while loop.

A simplified version of this portion of the game code looks like this:

var i = 1,
angle = 0,
minAngle = 12,
maxAngle = 40,
randomSectors = [0];
do {
      angle = getRandom(minAngle,maxAngle) + randomSectors[i-1];
      randomSectors.push(angle);
      i++;                                           
} while (angle < 360)

Inside the loop, the variable angle will be randomly assigned a value between 12 and 40 degrees, added to the value that was previously pushed into the randomSectors array. As the loop continues, angle constantly creeps towards 360, which the condition at the end detects for; if the condition is true, the loop is terminated. Because the angle amount is random, I don’t know how many sectors will be generated, but I know it will be at least one.

while

In a while loop, the condition is always evaluated first. This means that the loop may never execute, or even (potentially) loop an infinite number of times. The structure of a while loop looks like this:

while (condition) {
    statements;
} 

A good example might be tossing a coin to make a decision. Subconsciously only wanting the path associated with “heads”, you’ll just keep flipping the coin until it turns up that way:

function coinFlip() {
    return (Math.floor(Math.random() * 2) === 0);
}
var tossUp = coinFlip();

while (tossUp === false) {
    console.log("Not heads, darnit. Flipping again…");
    tossUp = coinFlip();
}
console.log("Heads is true! Yay!");

In this code, the while loop may never be run, since tossUp could be immediately set to true, avoiding the loop entirely. Theoretically, the while loop might forever write "Not heads, darnit. Flipping again…" to the console: if the initial value of tossUp was false, and the call to the function made inside the loop always yielded the same result, the loop would never exit. Of course, the most likely result is that “Not heads” is written to the console once or twice before the loop is exited and "Heads is true" is written.

Conclusion

As with most things, the trick to while and do… while loops lies not only in knowing them, but understanding where to apply them, a skill that can only be learned with practical applications in lots of coding. There are still other that have other applications, which I will cover in upcoming articles.

Photograph by tunnelphotography, used under a Creative Commons license

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.