Chapter V · Control Flow
The while Loop
A while loop keeps running as long as its condition stays true, which makes it the right shape when you don't know in advance how many times you'll need to repeat.
01 What Is the while Loop?
while checks a single condition before every iteration, including the very first. There's no built-in initialization or update clause the way for has — those have to be written separately, before the loop and inside its body.
02 Simple Example
Counting up while below a limit.
let count = 0;\n\nwhile (count < 3) {\n console.log(count);\n count++;\n}
The condition is re-checked after every pass; once count reaches 3, count < 3 is false and the loop ends without a fourth iteration.
03 How It Works
Because the condition is checked before the body runs, a while loop can execute zero times — if the condition is already false the first time it's checked, the body never runs at all. This is the key difference from do...while.
04 Step-by-Step
Evaluate the condition.
If false, exit — the loop is done.
If true, run the loop body.
Go back to step 1 and re-check the condition.
05 Common Mistakes & Edge Cases
Warning: Forgetting to update the variable that the condition depends on creates an infinite loop — while (energy > 0) with nothing decrementing energy inside the body never terminates and will freeze a single-threaded environment like the browser tab.
while is a good fit for conditions driven by external state — waiting for a value to change, reading from a stream, or polling — where the number of iterations genuinely isn't known ahead of time.
06 Mental Model
"Playing a level while lives remain — you check before every attempt, and zero lives means you never play at all."
07 Interview Questions
Q: Can a while loop run zero times?
Yes — if the condition is falsy on the very first check, the body is skipped entirely, unlike do...while which always runs at least once.
Key Takeaway
while re-checks its condition before every pass, including the first — meaning it may run zero times — and is the natural choice when the number of iterations depends on runtime state rather than a counter.