while Loop in JavaScript
while repeats while its condition stays truthy, testing before each pass — including the first, so the body may run zero times. It fits open-ended repetition with unknown endpoints: polling, retrying, consuming streams.
The update lives inside the body, so forgetting it builds an infinite loop that (in browsers) freezes the tab — the single-threaded event loop can't interleave. Structure conditions to guarantee progress toward falsiness.
Test-first repetition
while (n > 0) checks before every pass — starting falsy means zero executions.
Update inside the body
Something must move toward termination, or the loop (and the tab) never ends.
Polling and retries
while (!ready && attempts < max) combines condition with bounded retries — open-ended but capped.
Async while needs awaits
Polling with delays uses while + await sleep() — a bare tight loop starves the event loop forever.
let n = 5;let fact = 1;while (n > 1) { fact *= n; n--;}console.log(fact);Runs once per unit the condition counts down over.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.