while
Checks the condition first, then runs the block if it is true.
while loops repeat while a condition stays true. They are useful when the number of repeats depends on changing state.
let attempts = 0;
while (attempts < 3) {
attempts += 1;
console.log(`Attempt ${attempts}`);
}
Control Flow
A while loop checks its condition before every iteration. If the condition is false at the start, the loop body never runs.
A do...while loop runs the body once before checking the condition. That makes it useful when the first run must always happen.
while loops are common for queues, retries, reading from a stream, walking through linked data and repeating until a changing condition is complete.
Checks the condition first, then runs the block if it is true.
Runs once, then checks whether to repeat.
Something inside the loop must move the condition toward false.
Keep processing while items remain.
Examples
const queue = ["validate", "save", "notify"];
while (queue.length > 0) {
const task = queue.shift();
console.log(`Run ${task}`);
}
let isRunning = true;
while (isRunning) {
console.log("Still running");
}
// Nothing changes isRunning, so the loop never ends.
Rules that matter
Control flow decides which path code takes. Keep that path visible: name conditions, protect loop boundaries, avoid accidental fallthrough and use early exits only when they make the main path clearer.
The loop body must eventually make the condition false.
Retries and external data should have a maximum number of attempts.
Only use it when the body must run at least once.
Queue mutation or counter updates should be visible.
Long synchronous loops can freeze the browser.
If the repeat count is fixed, a for loop usually reads better.
Production thinking
while loops are flexible because they depend on live state. That same flexibility makes them dangerous if the state never changes.
A blocked browser prevents users from interacting with the page, including keyboard and assistive technology users.
Production while loops should have clear exit conditions, logging for retries and defensive limits around external data.
A loop that blocks rendering can delay or prevent important content from becoming available.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
Read each question out loud and answer it without looking at the examples. Control flow only clicks when you can trace the path in your own words.