Academic Block

JavaScript while and do…while Loops Get Certified

In addition to the for loop, JavaScript provides two other looping structures: the while loop and the do...while loop. Both repeat a block of code as long as a condition remains true.

The main difference between them is when the condition is checked: before each iteration for while, or after each iteration for do...while.

In this lesson, you will learn the syntax of both loops, when to use each one, and how to avoid some common pitfalls.

The while Loop

A while loop checks its condition before running the loop body. If the condition is false from the start, the loop body never runs at all.

What this code does: A while loop checks the condition before each iteration. As long as count <= 5, it prints the number and increases count. Output: 1 through 5.

let count = 1;
while (count <= 5) {
    console.log(count);
    count++;
}

This loop prints the numbers 1 through 5, stopping once count becomes greater than 5.

A while Loop That Never Runs

Because the condition is checked first, the loop body may run zero times.

What this code does: Because count starts at 10, the condition count <= 5 is already false, so the loop body never runs. Only the message after the loop is printed.

let count = 10;
while (count <= 5) {
    console.log(count);
    count++;
}
console.log("Loop finished. Count is:", count);

Since count starts at 10, the condition count <= 5 is false right away, so the loop body never executes.

The do…while Loop

A do...while loop runs the loop body first, and only checks the condition afterward. This guarantees the loop body runs at least once, no matter what.

What this code does: A do...while loop runs the body first, then checks the condition. It still counts from 1 to 5, but the structure guarantees at least one run even if the condition starts false.

let count = 1;
do {
    console.log(count);
    count++;
} while (count <= 5);

Notice the semicolon after while (count <= 5). This is required syntax for a do...while loop.

do…while Always Runs at Least Once

Unlike while, a do...while loop runs its body once even if the condition is false from the very beginning.

What this code does: Here count starts at 10, so a normal while would skip the body. With do...while, the body runs once, prints the message, then the condition fails and the loop stops.

let count = 10;
do {
    console.log("This runs at least once. Count is:", count);
    count++;
} while (count <= 5);

Even though count starts at 10 and the condition is immediately false, the console still prints the message once before the loop exits.

while vs. do…while

Aspect while do…while
Condition checked Before the loop body runs After the loop body runs
Minimum number of runs 0 (may never run) 1 (always runs at least once)
Requires trailing semicolon No Yes

break and continue

Just like the for loop, both while and do...while loops support break (to stop the loop entirely) and continue (to skip to the next iteration).

What this code does: Inside a while loop, continue skips even numbers and break stops the loop when i goes above 7. Only the odd numbers 1, 3, 5, 7 are printed.

let i = 0;
while (i < 10) {
    i++;
    if (i % 2 === 0) {
        continue;
    }
    if (i > 7) {
        break;
    }
    console.log(i);
}

This loop skips even numbers with continue, and stops entirely with break once i exceeds 7.

Avoiding Infinite Loops

Unlike a for loop, a while or do...while loop does not have a built-in update expression. It’s your responsibility to make sure something inside the loop eventually makes the condition false.

What this code does: An infinite-loop example is shown commented out so it cannot freeze the page. Forgetting to update the loop variable (e.g. missing count++) means the condition never becomes false.

// Be careful! This is an example of an infinite loop.
// let count = 1;
// while (count <= 5) {
//     console.log(count);
//     // Missing count++ here means the condition never becomes false.
// }
console.log("Always update your loop variable inside the loop body.");

Looping Until a Condition Is Met

while loops are especially useful when you don’t know in advance exactly how many times a loop needs to run, such as when processing data until some condition changes.

What this code does: A practical while loop: keep withdrawing 200 while the balance is at least 200. After the loop we print how many withdrawals were made and the remaining balance.

let balance = 1000;
let withdrawalCount = 0;
while (balance >= 200) {
    balance -= 200;
    withdrawalCount++;
}
console.log("Withdrawals made:", withdrawalCount);
console.log("Remaining balance:", balance);

Here, we don’t know in advance how many withdrawals will fit within the balance, so a while loop is a natural fit.

Practical Example: do…while

A do...while loop is a good fit when you need to perform an action at least once before checking whether to repeat it, such as validating input.

What this code does: A do...while is a natural fit for “try at least once” logic, such as password attempts. It tries each code until the correct one is found or attempts run out.

let attempts = 0;
const correctCode = "1234";
const enteredCodes = ["0000", "1111", "1234"];
let accessGranted = false;
do {
    const entered = enteredCodes[attempts];
    console.log("Attempt " + (attempts + 1) + ": trying " + entered);
    if (entered === correctCode) {
        accessGranted = true;
    }
    attempts++;
} while (!accessGranted && attempts < enteredCodes.length);
console.log("Access granted:", accessGranted);
console.log("Total attempts:", attempts);

Common Mistakes With while and do…while

  • Forgetting to update the loop variable inside the loop body, causing an infinite loop.
  • Forgetting the semicolon after the while (...) condition in a do...while loop.
  • Assuming a while loop always runs at least once, when it might not run at all if the condition starts false.
  • Using a while loop when a for loop would be clearer, especially when the number of iterations is already known.
  • Placing the update expression before a continue statement incorrectly, which can accidentally skip it and cause an infinite loop.

Best Practices for while and do…while

  • Use while when the number of iterations isn’t known in advance and depends on a changing condition.
  • Use do...while when the loop body must run at least once regardless of the condition.
  • Always ensure the loop variable is updated somewhere inside the loop body.
  • Prefer a for loop when you already know exactly how many times to iterate.
  • Keep the condition simple and easy to reason about at a glance.

Quick Summary

  • A while loop checks its condition before each iteration and may never run.
  • A do...while loop checks its condition after each iteration and always runs at least once.
  • Both loops support break and continue.
  • Neither loop has a built-in update expression, so you must update the loop variable manually inside the loop body.
  • while is a good fit when the number of iterations isn’t known ahead of time.
  • do...while is useful when an action must happen at least once before checking a condition.

Try It Yourself

Modify the code below. Try changing the starting value of count to something greater than 5 and compare how the while and do...while versions behave differently.

What this code does: Practice comparison: with count = 6, the while loop never runs, but the do...while runs once. Change the starting value and click Test My Code to explore the difference.

let count = 6;
console.log("--- while loop ---");
while (count <= 5) {
    console.log(count);
    count++;
}
console.log("--- do...while loop ---");
count = 6;
do {
    console.log(count);
    count++;
} while (count <= 5);
Tip: If you ever need code to run at least once no matter what — like showing a menu before checking whether the user wants to continue — reach for do...while instead of adding an extra copy of the code before a regular while loop.

Understanding while and do...while loops is essential before moving on to functions, arrays, and more advanced JavaScript concepts.

🧪 Test Your JavaScript Code

Edit the code on the left and click “Run Code” to see the console output on the right.

📝 JavaScript Code
👁 Console Output

Click “Run Code” to see the output here.

Ctrl + Enter to run code Esc to close