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.
while (queue.length > 0) { handle(queue.shift()); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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...whilewhen 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 onbreakorreturn. continuepitfall. In awhileloopcontinuejumps straight back to the condition. If the update statement is below thecontinue, it is skipped, which can cause an endless loop. Update the variable beforecontinue.- 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
forbecause the initializer, test and update sit together. - Browser caution. A long synchronous
whileloop blocks the page; waiting for something with a busy loop (while (!ready) {}) never lets the event loop run, soreadycan never change. Use promises, events or timers. - Labels let
breakandcontinuetarget an outer loop.
Browser support
Supported in every JavaScript engine.
Related
do...while,for,break,continue- Lessons: while loops, break and continue