Lesson 3: The do…while Loop

Learning Objectives

By the end of this lesson, learners will:

  • Understand the structure and purpose of the do...while loop
  • Know how it differs from while and for loops
  • Learn when to use it (especially when code should run at least once)
  • Avoid common mistakes such as infinite loops
  • Practice creating interactive do...while loops for input validation and repetition

What Is a do...while Loop?

A do...while loop is a type of loop that:

  • Always runs the code at least once
  • Then checks the condition after running the code

This is what makes it different from a regular while loop, which checks the condition before running.


Syntax of do...while

do {
  // code to run
} while (condition);

The code block runs first, then the condition is checked.


Real-Life Analogy

Think of a restaurant feedback form:

The waiter gives you the form before asking if you want to fill it out.
You may return it empty, but you’re handed the form regardless.

This is the logic of do...while: you always get one run, no matter what.


Basic Example

let i = 1;

do {
  console.log("Loop run #" + i);
  i++;
} while (i <= 3);

Output:

Loop run #1
Loop run #2
Loop run #3

Even though it’s like a while loop, the first iteration happens no matter what.


Contrast with while Loop

Using while:

let i = 10;
while (i < 5) {
  console.log("This will not run");
}

Output: Nothing — the condition is false from the start.

Using do...while:

let i = 10;
do {
  console.log("This runs once, even if i < 5 is false");
} while (i < 5);

Output:

This runs once, even if i < 5 is false

Real-World Use Case: Password Prompt

let password;

do {
  password = prompt("Enter your password:");
} while (!password);

console.log("Thanks for entering a password!");

The prompt will always appear at least once, even if the user hits cancel or leaves it empty.


Another Use Case: Menu Selection

let choice;

do {
  choice = prompt("Choose 1 for Info, 2 for Help, 0 to Exit");
} while (choice !== "0");

console.log("Goodbye!");

The menu keeps showing until the user types “0”.


Watch Out for Infinite Loops

Just like other loops, if your condition never becomes false, the do...while loop will run forever.

✅ Always make sure:

  • You change the variable inside the loop
  • The condition is realistic and achievable