Favorites

JavaScript while Statement

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
while
JavaScript IterationThis statement is supported by all modern browsers.
Updated 28th November 2026

The while statement repeats a block of code as long as a condition stays truthy, checking the condition before each pass.

Description

The while statement runs its body as long as the condition is truthy, testing the condition before each iteration. If it's false at the start, the body never runs. It suits loops where you don't know the number of iterations in advance, such as reading until there's no more data.

Make sure something in the body eventually makes the condition false, or use break, to avoid an infinite loop that freezes the page.

A while loop is a good fit when the number of iterations depends on something that changes inside the loop, such as removing items from a queue, waiting for a condition in a game loop, or following links in a linked list. When you know how many times to loop, or you're iterating over a collection, for or for...of usually express the intent more clearly. while (true) with a break inside is a common pattern for loops whose exit condition is easiest to check in the middle.

Syntax

while (condition) {
  statements
}

Example

let n = 1;
while (n < 50) {
  n *= 3;
}
console.log(n);

const queue = ['a', 'b', 'c'];
while (queue.length) console.log('Processing', queue.shift());

Browser Support

The following information will show you the current browser support for the while statement. Hover over a browser icon to see the version that first introduced support for this statement.

This statement is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee