Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 156 ยท Control Flow

while and do...while

Learn JavaScript while and do...while loops, when to choose them over for, how to write conditions that end, and how to avoid infinite loops.

A for loop is perfect when you know the number of repetitions up front: 10 rows, 5 attempts, every item in an array. But sometimes you don't know how many steps you'll need. How many times do you halve a number before it drops below 1? How many dice rolls until you get a six? How many pages of results are left? In these cases you only know the condition that should end the loop.

That's the job of the while loop: keep going while something is true. Its sibling, do...while, does the same but always runs at least once. This lesson covers both, shows how to choose between them and for, and spends some time on the danger they share: the loop that never ends.

The while loop

A while loop has just a condition and a body:

JavaScript
while (condition) {
  // body
}

Before each iteration, JavaScript checks the condition. If it's truthy, the body runs and the check repeats. If it's falsy, the loop ends and the program continues after the closing brace. If the condition is falsy right away, the body never runs at all.

JS Halving until small

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You couldn't easily write this as a for loop with a fixed count, because the number of steps is the answer you're looking for.

Notice the three ingredients every while loop needs, because nothing in the syntax enforces them:

  1. Setup before the loop: here, amount and steps get their starting values.
  2. A condition that is checked each time: amount >= 1.
  3. Progress inside the body: amount shrinks, so the condition will eventually be false.

A for loop puts all three in its header. A while loop scatters them, so it's on you to make sure each one is there.

for and while are interchangeable

Any for loop can be written as a while loop, and vice versa:

JavaScript
// for
for (let i = 0; i < 3; i++) {
  console.log(i);
}

// the same as while
let i = 0;
while (i < 3) {
  console.log(i);
  i++;
}

So the choice is about readability. Use for when you're counting or stepping through indexes. Use while when you're waiting for a condition, and the number of iterations isn't known in advance.

JS Rolling until a six

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Run it several times: the number of iterations changes every time. (The Math lesson explains the random-number formula.)

The do...while loop

Look at the dice example again. We had to call rollDie() once before the loop, then again inside it, because a while loop checks its condition first. When the body must run at least once, do...while removes that duplication. It runs the body first and checks the condition afterwards:

JavaScript
do {
  // body: always runs at least once
} while (condition);

Note the semicolon after the condition. It's the one place where a loop ends with ;.

JS do...while

Press Run (or Ctrl + Enter) to see the console output here.

No output.

do...while is less common than the other loops, but it's the natural fit for "do something, then decide whether to do it again": retrying an operation, generating a value until it's valid, or asking a question until the answer is acceptable.

let scope with do...while. A variable declared with let inside the do block isn't visible in the while (โ€ฆ) condition, because the condition sits outside the braces. That's why roll is declared before the loop in the example above.

Processing until something runs out

A very common while pattern consumes a collection until it's empty, such as a queue of tasks where each task might add more work:

JS Working through a queue

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A for loop over the original length would miss the "iron" task that was added halfway through. The while loop doesn't care how long the queue is; it just keeps going until there's nothing left.

The same shape works for digit-by-digit number processing:

JS Summing digits

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Infinite loops

If the condition never becomes falsy, the loop never ends. This is an infinite loop, and it's the classic while mistake. In a browser tab, JavaScript runs on the same thread that draws the page and handles clicks, so an infinite loop freezes the whole page until the browser offers to kill it. (Our editors run your code separately and have a Stop button, so experiment freely.)

The usual causes:

  • Forgetting the progress step. while (i < 10) { console.log(i); } with no i++.
  • Progress in the wrong direction. i-- when the condition expects i to grow.
  • A condition that can skip past its target. Watch this one:
JavaScript
let x = 0;
while (x !== 1) {
  x += 0.1; // 0.1 + 0.1 + ... never lands exactly on 1
}

Because of floating-point rounding (see Numbers), x goes from 0.9999999999999999 straight to 1.0999999999999999. It never equals 1 exactly, so !== stays true forever. Using x < 1 instead of x !== 1 fixes it, because a range check can't be "jumped over".

Add a safety limit while developing. When a loop depends on something you don't fully control, count the iterations and stop at a sensible maximum: while (!done && attempts < 1000). It costs one line and turns a frozen page into a clear bug you can investigate.

Intentional infinite loops

Sometimes you do write while (true) on purpose. The loop runs until code inside decides to leave with break or return. That is useful when the exit check naturally falls in the middle of the body rather than at the start or end:

JavaScript
while (true) {
  const answer = getNextAnswer();
  if (answer === "quit") break;
  handle(answer);
}

You'll learn break properly in the next lesson.

Choosing a loop

You knowโ€ฆ Use
How many times to repeat, or you need a counter for
Only the condition that keeps the loop going while
The body must run at least once before checking do...while
You want each item of an array, string, Map or Set for...of (coming soon)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many times does the body of let n = 5; while (n < 3) { n++; } run?

    A while loop checks the condition first. 5 < 3 is false, so the body never runs.
  2. 2. What is the key difference between while and do...while?

    do...while runs the body first and tests the condition afterwards, so the body always runs at least once.
  3. 3. Why might while (x !== 1) { x += 0.1; } never end when x starts at 0?

    Adding 0.1 repeatedly produces values like 0.9999999999999999 and then 1.0999999999999999. A range check like x < 1 is safer.
  4. 4. When is a while loop a better choice than a for loop?

    while reads best when you're waiting for a condition, such as a queue becoming empty or a random value appearing.

Summary

  • while (condition) { โ€ฆ } checks the condition before each iteration and may run zero times.
  • do { โ€ฆ } while (condition); checks after each iteration, so the body runs at least once.
  • Every while loop needs setup, a condition and progress toward ending, and nothing enforces them, so check all three.
  • Prefer for for counting and while for "until something changes".
  • Infinite loops come from missing or wrong-direction progress, or conditions that can be skipped over. Prefer range checks (<) to exact checks (!==).
  • while (true) with an inner break is a deliberate pattern for exits in the middle of a loop.

Next: break, continue and Labels โ€” leaving a loop early and skipping iterations.