JavaScript while Statement
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
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.
Desktop





Tablets & Mobile





