while
In JavaScript, the while keyword starts a loop that checks a condition before each pass and runs its body for as long as the condition is truthy. If the condition is falsy from the start, the body never runs. The same keyword also closes a do...while loop, which starts with do and checks its condition after each pass, so its body always runs at least once.
The condition can be any expression, and JavaScript converts its result to a boolean. Inside the body, break ends the loop and continue jumps back to the condition. A while loop has no initializer or update step, unlike for, so any counter is declared before the loop and updated in the body.
JavaScript while Keyword Syntax
A while loop runs a single statement or a block:
while (<condition>) <statement>
while (<condition>) {
<statements>
}
JavaScript while Keyword Examples
A while loop repeats its body as long as the balance stays under 150:
> let balance = 100;
undefined
> let months = 0;
undefined
> while (balance < 150) {
… balance *= 1.1;
… months += 1;
… }
5
> months
5
The loop tests balance before each pass and stops once it’s 150 or more, which takes five passes. The REPL echoes 5 because that’s the value of the last statement the body ran.
A condition that’s falsy on the first check skips the body entirely:
> while (false) {
… console.log("Never printed");
… }
undefined
The body never runs, so nothing is printed, and the REPL echoes undefined because the loop ran no statements.
JavaScript while Keyword Use Cases
- Repeating work until a condition changes, when the number of passes isn’t known in advance
- Consuming items from a queue or stack until it’s empty
- Polling or retrying until a value reaches a target
- Running a main loop with
while (true)that ends throughbreakorreturn
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 4, 2026