Learn JavaScript
❯ control_flow.do_while_loop

do-while Loop in JavaScript

$concept

do-while tests at the bottom: the body always runs at least once, then repeats while the condition holds. That guarantee makes it the prompt loop — show/do first, then ask whether to continue.

The trailing semicolon (} while (...);) is mandatory. Prefer plain while when zero iterations must be possible; reach for do-while exactly when the first pass is unconditional.

$how it works
1

Body first, test after

do { ... } while (cond); runs the block, then checks — one execution guaranteed.

2

Don't forget the semicolon

The closing }; is required and unique among loops.

3

Prompts are the use case

Do the thing, then test whether to repeat — the action must precede any decision about it.

4

while vs do-while

Zero-or-more means while; one-or-more means do-while.

$example
let shows = 0;
let choice;
do {
shows++;
choice = 9;
} while (choice !== 9);
console.log("shown", shows);
Output
shown 1
1The body runs unconditionally: shows becomes 1, choice becomes 9.
2The bottom test is immediately false — single guaranteed pass, then exit.
3A top-tested while with preset 9 would have run zero times.
$use cases
Menu and prompt loops showing options before reading choices
Retry patterns (attempt, validate, repeat while invalid)
First-run-unconditional setup sequences
Post-test repetition wherever the action precedes the decision

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.