CodeBlanks Logo Icon CodeBlanks

The do...while loop

JavaScript course · Beginner · Lesson 38/133

Learn do...while that runs at least once and how it differs from while.

The do...while loop

The do...while loop runs the body first, then tests the condition. So the body always runs at least once. This is called a post-condition loop.

let i = 1;
do {
  console.log(i);
  i++;
} while (i <= 3);

Here i is printed with its current value, then incremented. The loop continues while i <= 3 is true. Output: 1, 2, 3. Even if the condition is false at the start, the body still runs once.

When to use do...while?

The do...while loop is handy when the body must run at least once. A classic example is rolling a die until you get the wanted result.

let roll;
do {
  roll = Math.floor(Math.random() * 6) + 1;
  console.log(roll);
} while (roll !== 6);

Here the die is rolled at least once. If it shows 6, the loop ends; otherwise it rolls again. This way you wait for a random event to meet a condition.

Exercise Print 1 to 3

Use a do...while loop to print the numbers 1 to 3 with console.log. Increment the counter each step.

Show example solution
let i = 1;
do {
  console.log(i);
  i++;
} while (i <= 3);

Exercise Roll a die until you get 6

Use a do...while loop to roll a die. Each step, generate a value 1–6 with Math.floor(Math.random() * 6) + 1 and assign it to roll. Print it with console.log(roll). Keep going until you roll a 6.

Show example solution
let roll;
do {
  roll = Math.floor(Math.random() * 6) + 1;
  console.log(roll);
} while (roll !== 6);

Test yourself

  1. When is the condition tested in a do...while loop?

    • Before the loop
    • Only on the first step
    • After each run of the body
    • Only on errors
    Show answer

    After each run of the body — do...while runs the body first, then tests the condition. That's why the body always runs at least once.

  2. Complete the do...while that prints 1, 2, 3

    let i = 1;
    do {
      console.log(i);
      i++;
    } while (i !== ____);
    Show answer
    let i = 1;
    do {
      console.log(i);
      i++;
    } while (i !== 4);
  3. Match the loop type to the scenario

    for
    known count of repeats
    while
    unknown upfront condition
    do...while
    runs at least once

All lessons in Beginner