References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript while statement

Statement JavaScript All modern browsers Updated
Quick answer

The while loop runs a block over and over as long as its condition is true, checking before each pass. while (i < 10) { ... }. Use it when you don't know the number of iterations in advance. Make sure something inside changes the condition, or you get an infinite loop.

Overview

A while loop keeps running its body for as long as the condition is true, testing it before every pass. It shines when you don't know up front how many times you'll loop — reading until input runs out, retrying until something succeeds, processing a queue until it's empty. If the condition is false to begin with, the body never runs at all.

The hazard to respect is the infinite loop. Something inside the body must eventually make the condition false — increment a counter, shrink a list, flip a flag. Forget that and the loop runs forever, freezing the page. It's the single most common while bug, so always check that the exit condition is reachable.

Its close relative do...while puts the check at the end, so the body always runs at least once — handy for things like prompting until you get valid input. When you do know the iteration count or you're counting through indexes, a for loop is usually the clearer choice; while is for the open-ended cases.

Syntax

while (condition) {
  // runs while condition is true
}

// runs the body at least once
do {
  // ...
} while (condition);

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  let n = 1;
  const powers = [];

  // double until we pass 100
  while (n <= 100) {
    powers.push(n);
    n *= 2;
  }

  document.getElementById('out').textContent = powers.join(', '); // 1, 2, 4, ... 64
</script>

Best practices

  • Make sure the body changes something that will eventually end the loop, to avoid an infinite loop.
  • Use while for open-ended repetition; use a for loop when you know the count.
  • Reach for do...while when the body must run at least once.
  • Use break for an early exit and continue to skip to the next check.

Frequently asked questions

What is the difference between while and for?
A for loop bundles the counter setup, condition and step in its head — ideal for a known count. while just takes a condition, suiting open-ended loops.
What is an infinite loop and how do I avoid it?
A loop whose condition never becomes false, so it runs forever. Avoid it by ensuring the body updates something that moves toward the exit condition.
What is the difference between while and do...while?
while checks the condition before the body, so it may run zero times; do...while checks after, so the body always runs at least once.
How do I stop a while loop?
Make the condition false, or use break to exit immediately.