Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Statements and Declarations

The while statement

Reference for the JavaScript while loop: how the condition is checked before each pass, infinite loops, break and continue, and when to use for instead.

The while statement repeats a statement as long as its condition is truthy. The condition is checked before every iteration, so the body may run zero times. Use while when you do not know in advance how many passes you need: reading until a value runs out, retrying, searching, or waiting for a state to change.

JavaScript
while (queue.length > 0) {
  handle(queue.shift());
}

Try it

JS Looping until a condition fails

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

No output.

JS Collatz steps with break and continue

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

No output.

Syntax

JavaScript
while (condition) {
  statement
}
Part Description
condition An expression evaluated before each iteration; converted to a boolean.
statement The body, usually a block. It must eventually make the condition falsy, or leave with break, return or throw.

Usage notes

  • Check first. If the condition is falsy at the start, the body never runs. Use do...while when it must run at least once.
  • Infinite loops. Forgetting to change the variable that the condition tests freezes the page or program. while (true) is a deliberate form that relies on break or return.
  • continue pitfall. In a while loop continue jumps straight back to the condition. If the update statement is below the continue, it is skipped, which can cause an endless loop. Update the variable before continue.
  • Assignment in the condition (while ((m = re.exec(text)))) is a known idiom, written with extra parentheses to show it is intentional.
  • Counting loops are clearer as for because the initializer, test and update sit together.
  • Browser caution. A long synchronous while loop blocks the page; waiting for something with a busy loop (while (!ready) {}) never lets the event loop run, so ready can never change. Use promises, events or timers.
  • Labels let break and continue target an outer loop.

Browser support

Supported in every JavaScript engine.