Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Loops and Control Flow  ›  Lesson

while and do...while

while 10 minwhile checks its condition before the body runs, so the body can run zero times; do...while checks after, so the body always runs at least once, even when the condition starts out false.

while and do...while

In short: both loops repeat a body while a condition holds — the difference is when they check. while (condition) { ... } checks before the body, so if the condition starts false, the body never runs at all. do { ... } while (condition); checks after, so the body always runs at least once, even if the condition was already false before the loop began. Same repetition, opposite guarantee.

Two doors: on the left, while's door is checked FIRST, so if the condition is already false the room (body) is never entered, 0 times; on the right, do-while's door is checked AFTER the room, so the body runs once no matter what

Serving a queue until it's empty

A ticket counter serves people one at a time until nobody's left:

javascript

Before each lap, while asks "is queue > 0?" Three yeses, then a no, and the loop stops. Change the starting value and the loop adapts automatically — that's the point of checking the condition every time, not counting laps in advance.

An already-empty queue

Now start with nothing in the queue:

javascript

empty > 0 is false on the very first check, before the body ever runs, so while skips it entirely — exactly the right behaviour for "don't serve an empty queue."

A do-while that runs once no matter what

Compare that with do...while, whose door is on the other side:

javascript

tries < 0 is false before the loop even starts, but do...while runs the body first, then checks — so the message prints once regardless. This is the right shape for things that must happen at least once, like showing a menu before asking whether to repeat it — and the wrong shape for anything that should be skippable when there's nothing to do, like the queue above.

Quick practice

quick drill

let n = 0; while (n > 0) { console.log(n); } — how many times does it print?

quick drill

let n = 0; do { console.log(n); } while (n > 0); — how many times does it print?

quick drill

Which loop is the right choice for "ask the user a question, and keep asking again if they say no"?

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainZero times or one time?

A queue starts empty (queueLength = 0). Explain what while (queueLength > 0) { serve(); } does versus do { serve(); } while (queueLength > 0);, and why the choice matters here.