Do-While Loop

Think about eating at a new restaurant. 🍛

You first taste the food, and then decide: "Is it good? Should I order more?"

You can't decide whether you like the food before tasting it. You must try it at least once.

In the last lesson, the while loop checked the condition first, and then ran the code. So if the condition was false at the start, the code never ran at all.

But sometimes we want the code to run at least once, no matter what, and then check the condition. For this, JavaScript gives us the do-while loop.

What Is a Do-While Loop?

A do-while loop runs the code first, and then checks the condition. If the condition is true, it repeats. So the code always runs at least once.

  • while loop: Check first, then run. 🤔 → 🏃
  • do-while loop: Run first, then check. 🏃 → 🤔

Syntax

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

Key points about the syntax:

  • The code block { } comes first, after the keyword do.
  • The while (condition) comes at the end.
  • Notice the semicolon ; after while (condition). It is required here, unlike in the normal while loop!

Your First Do-While Loop

How It Works, Step by Step

StepActionValue of countCondition count <= 5
Round 1Print "Count: 1", then count++becomes 2✅ true → repeat
Round 2Print "Count: 2", then count++becomes 3✅ true → repeat
Round 3Print "Count: 3", then count++becomes 4✅ true → repeat
Round 4Print "Count: 4", then count++becomes 5✅ true → repeat
Round 5Print "Count: 5", then count++becomes 6❌ false → stop

The flow:

Run code → Check condition → true → Run code → Check condition → ...
                  ↓ (false)
              Exit the loop

The Big Difference: It Always Runs at Least Once

Let us see what happens when the condition is false from the very beginning.

With a while loop

The condition 10 < 5 is false, so the code never runs.

With a do-while loop

The code runs once first, and then JavaScript checks 10 < 5. It is false, so the loop stops. But the code already ran one time!

Remember: A do-while loop runs at least once, even if the condition is false from the start.


Real-Life Examples

The do-while loop is perfect when you must do something first and then decide whether to repeat it.

Example 1: ATM PIN entry 🏧

The ATM must ask for the PIN at least once. If it is wrong, it asks again, up to 3 attempts.

The ATM has to ask at least once, which makes this a perfect fit for do-while.

Example 2: Menu-driven program 📋

A menu should be shown at least once, and then repeat until the user chooses "Exit."

The menu always shows at least once, even if the user wants to exit right away.

Example 3: Rolling a dice until you get 6 🎲

In games like Ludo, you must roll at least once, and you keep rolling until you get a 6.

We don't know how many rolls it will take, but we know we must roll at least once.

Example 4: Adding the digits of a number

Why do-while here? Even if the number is 0, it has one digit that should be processed. A do-while makes sure it runs at least once.


Infinite Loops ⚠️

Just like the while loop, if the condition never becomes false, the loop never stops.

let i = 1;

do {
  console.log(i);
  // ❌ forgot i++ → runs forever!
} while (i <= 5);

How to avoid it:

  • ✅ Always update the variable inside the loop.
  • ✅ Make sure the update moves toward making the condition false.

While vs Do-While vs For

PointFor LoopWhile LoopDo-While Loop
Condition checkedBefore each roundBefore each roundAfter each round
Minimum runs001
Best whenNumber of repeats is knownNumber of repeats is unknownCode must run at least once
Semicolon at end?NoNoYes while (...);
ExamplePrint a table from 1 to 10Save money until a goalShow a menu, ask for a PIN

Simple way to remember:

  • "Do this 10 times" → for
  • "Keep doing this while..." → while
  • "Do this once, then repeat if needed" → do-while

Common Mistakes to Avoid

❌ Mistake 1: Forgetting the semicolon

do {
  console.log("Hello");
} while (false)    // ⚠️ semicolon missing

It often still works, but always add the semicolon to keep your code clean and safe:

} while (false);   // ✅

❌ Mistake 2: Using do-while when the code should not run

let cartItems = 0;

do {
  console.log("Processing payment...");   // ❌ runs even with an empty cart!
} while (cartItems > 0);

If the code should not run when the condition is false, use a normal while loop instead.

❌ Mistake 3: Declaring the variable inside the loop

do {
  let i = 1;   // ❌ resets every round
  i++;
} while (i <= 5);   // ❌ ReferenceError: i is not defined

Variables used in the condition must be created before the do block.


Quick Summary Table

ConceptExample
Basic do-whiledo { ... i++; } while (i <= 5);
Runs once even if falsedo { ... } while (false);
Repeat until the correct inputdo { ask(); } while (input !== correct);
Menu loopdo { showMenu(); } while (choice !== exit);

Key Takeaways

  • A do-while loop runs the code first, then checks the condition.
  • It always runs at least once, even if the condition is false from the start.
  • It is perfect for menus, PIN or password entry, input validation, and games.
  • Don't forget the semicolon ; after while (condition).
  • Always update the loop variable to avoid infinite loops.