Course contentsShow
← JavaScript
Lesson 340 of 2,72310. LoopsFree lesson

The Do-While Loop

Discover do-while loops that execute at least once before checking the condition.

The Do-While Loop

You'll learn how the do-while loop guarantees at least one execution before checking its condition.

What Makes Do-While Different?

While a while loop checks its condition before each iteration, the do-while loop checks its condition after each iteration. This subtle difference has a significant consequence: the loop body always runs at least once, regardless of whether the condition is initially true or false.

Syntax

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

Notice the semicolon after the closing parenthesis — it's required!

How It Works

The execution flow follows these steps:

  1. Execute the loop body
  2. Check the condition
  3. If true, go back to step 1
  4. If false, exit the loop

When to Use It

Do-while loops shine when you need something to happen at least once before validating. Think of it like a restaurant asking "Would you like anything else?" — they only ask after you've placed your first order, not before you've ordered anything.

let userInput = '';

do {
  userInput = getMenuChoice(); // Always shows menu at least once
} while (userInput !== 'quit');

Even if userInput somehow started as 'quit', the menu would display once.

Common Pattern

let count = 5;

do {
  console.log(count); // Logs: 5
  count--;
} while (count > 10); // false immediately, but loop already ran once

Key Takeaway: The do-while loop guarantees execution before evaluation, making it perfect for scenarios where you need at least one iteration regardless of initial conditions.