Essential JavaScript

Do...While Loop

A do...while loop is similar to a while loop. The difference is that the do...while loop runs once before checking to see if it should run again.

This is useful when the code should run at least once even if the condition isn't true.

For example:

let i = 5;
do {
  console.log(i);
  i--;
}
while (i > 10);

In the above example, we will see 5 logged to the console, even though the condition i > 10 was never true.

The loop runs once, then it checks if it should run again.

Use Case

If we need to initialize some values using a loop, a do...while loop is a great choice.

For example, let's say we are writing the software inside a microwave oven. The microwave has a dial on it representing the power level, from 1 to 100.

We will receive a number between 1 and 100. However, the microwave can only produce 10 different levels of power, all divisible by 10.

We need to determine the power level (10, 20, etc.) from the input number:

function getPowerLevel(dialPosition) {
  let powerLevel = 0;
  do {
    powerLevel += 10;
  }
  while (powerLevel < dialPosition);
  return powerLevel;
}
console.log(getPowerLevel(1));
console.log(getPowerLevel(29));

In this example, we always bump powerLevel to 10, because that is the lowest setting.

Then we bump it higher if the dialPosition is still above the powerLevel.

This is a simple number example, but there are many other ways a do...while loop can be useful.


Learning Goals

Code Editor