The do...while Loop

Grade 5, page 5 of 11. A one-minute read.

There's one more kind of loop, and it's a slight twist on while. A do...while loop runs the body first, and then checks the condition. That means it always runs at least once:

JavaScript
let number = 100;

do {
  console.log(`The number is ${number}`);
  number++;
} while (number < 5);

It prints

The number is 100

Even though 100 < 5 is false right from the start, the body ran once before JavaScript checked. A normal while loop wouldn't have run at all.

This is useful when you need to do something before you can decide whether to repeat it. The classic example is asking a user for input until they give a valid answer. You have to ask at least once!

JavaScript
let age;

do {
  age = Number(prompt("Please enter your age (1 to 120):"));
} while (Number.isNaN(age) || age < 1 || age > 120);

alert(`Thanks! You are ${age}.`);

If the user types banana, or -5, or 500, the loop asks again. And again. And again. Until they cooperate. (Computers are very patient.)

do...while is the least commonly used loop, so don't worry if you rarely use it. Just know it exists.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning