Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 16 of 58

while and do...while loops

Repeat code until a condition changes with while and do...while, and learn when to choose them over for, plus how to avoid infinite loops.

10 minControl flowUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonWrite while and do...while loops that stop correctly, and choose between them and a for loop depending on whether you know the count in advance.

After this lesson you can write loops that repeat until something becomes true, rather than a fixed number of times. You already know the for loop from for loops. while is its simpler cousin: it has only the condition.

The while loop

javascript
while (condition) {
  // body: runs again and again while condition is true
}

Before each pass JavaScript evaluates the condition. If it is true, the body runs and then the check happens again. If it is false, the loop ends and the program continues after it.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  let count = 3;

  while (count > 0) {
    log("Counting down:", count);
    count--;
  }

  log("Go!");
</script>

The output is Counting down: 3, Counting down: 2, Counting down: 1 and Go!. The line count-- is essential. It is the part that moves the loop towards its end. In a for loop, the update lives in the header; in a while loop, you must remember to put it in the body.

When while beats for

A for loop is ideal when you know the number of passes, such as "once per item". A while loop suits cases where the number of passes depends on what happens along the way. For example, how many times can you halve 100 before it drops below 1?

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  let value = 100;
  let halvings = 0;

  while (value >= 1) {
    value = value / 2;
    halvings++;
  }

  log("Halvings:", halvings);
  log("Final value:", value);
</script>

This prints Halvings: 7 and Final value: 0.78125. You could not easily have guessed 7 in advance, and that is the sign a while fits.

do...while: run first, ask later

do...while flips the order. The body runs once, and only then is the condition tested. The loop therefore always runs at least once.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  let n = 10;

  while (n < 5) {
    log("while body runs");
  }

  do {
    log("do...while body runs once, n is", n);
  } while (n < 5);

  log("done");
</script>

The output is do...while body runs once, n is 10 and done. The while loop printed nothing, because 10 < 5 is false from the beginning. The do...while printed once before it noticed. Note the semicolon after the closing parenthesis of a do...while. It is the one loop that wants one.

Typical uses are "ask, then check the answer" flows, such as reading a value and repeating if it is not valid. In day-to-day code do...while is rare, but you should recognise it.

Avoiding infinite loops

A loop whose condition never becomes false is an infinite loop. In the browser it freezes the tab until the browser offers to stop the page. In Node.js it keeps the program running until you press Ctrl+C. Before running any while, ask yourself these questions:

  1. What variable does the condition depend on?
  2. What changes that variable inside the body?
  3. Does it change in the direction that makes the condition false?

When a loop depends on something outside your control, such as random numbers or data from a server, add a safety limit:

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  let attempts = 0;
  const maxAttempts = 20;
  let roll = 0;

  while (roll !== 6 && attempts < maxAttempts) {
    roll = Math.floor(Math.random() * 6) + 1;
    attempts++;
  }

  log(roll === 6 ? "Rolled a six" : "Gave up", "after", attempts, "attempts");
</script>

The result varies each run, but it always ends: either with a six or after at most 20 attempts. A safety limit like maxAttempts turns a possible freeze into a harmless message. Notice also that roll starts at 0 so that the loop is entered at all.

Looping until a condition inside the body

Sometimes the stopping rule is easier to write in the middle of the body than in the header. You can write while (true) and leave with break. That is covered in the next lesson, break, continue and labels, and it is a legitimate pattern as long as there is a reachable break.

Common mistakes

  • Forgetting to update the variable. Writing while (i < 10) with no i++ is the classic freeze. Write the update first, then fill in the rest of the body.
  • Updating in the wrong direction. i-- with i < 10 counts away from the limit forever.
  • A condition that is false from the start. If roll started at 6 in the last example, the loop would never run. Check your starting values.
  • Using = instead of === in the condition. while (x = 5) assigns 5 and is always truthy. This is the same slip as in an if statement.
  • Floating point conditions. while (x !== 1) with x += 0.1 may never hit exactly 1 because of rounding. Use <, <= or a counter.
  • Choosing while for a plain count. If you know the number of passes, for keeps the setup, test and update together in one line.

Exercise

  1. Use a while loop to add up the numbers 1, 2, 3, ... until the total is greater than 100. Log how many numbers you needed and the final total.
  2. Write a loop that doubles a number starting from 1 and stops before it passes 1000, logging each value.
  3. Rewrite the countdown example as a do...while. Then change the starting count to 0. What is different about the output, and why?

Next: break, continue and labels.

Key points

  • while checks its condition before each pass, so the body may run zero times.
  • do...while runs the body once first and checks afterwards, so it always runs at least once.
  • Something inside the loop must change the condition, or the loop never ends.
  • Use while when you do not know how many passes you need, and for when you do.
  • Keep a safety counter or a clear stopping rule when the loop depends on data you do not control.

Check yourself

1. What is the difference between while and do...while?
2. How many times does this body run? let n = 10; while (n < 5) { n++; }
3. Why does this loop never end? let i = 0; while (i < 3) { console.log(i); }
4. When is a while loop a better fit than a for loop?