Learn JavaScript
❯ control_flow.while_loop

while Loop in JavaScript

$concept

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.

$how it works
1

Test-first repetition

while (n > 0) checks before every pass — starting falsy means zero executions.

2

Update inside the body

Something must move toward termination, or the loop (and the tab) never ends.

3

Polling and retries

while (!ready && attempts < max) combines condition with bounded retries — open-ended but capped.

4

Async while needs awaits

Polling with delays uses while + await sleep() — a bare tight loop starves the event loop forever.

$example
let n = 5;
let fact = 1;
while (n > 1) {
fact *= n;
n--;
}
console.log(fact);
Output
120
1n starts at 5; each pass multiplies fact by n, then decrements.
2Passes compute 1*5*4*3*2 = 120, stopping at n == 1.
3Without n-- the tab would hang — the update is the termination argument.
$complexity
time O(n)
space O(1)

Runs once per unit the condition counts down over.

$use cases
Retry loops with attempt caps and backoff
Draining queues of unknown length
Polling with async delays between checks
Countdown and convergence loops

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.