while and do...while Loops: Condition-Driven IterationThe JavaScript while loop repeats a block of code as long as a given condition remains truthy. Unlike a for loop with a fixed count, while fits tasks where you do not know ahead of time how many passes are needed.
while vs. do...while Execution FlowThe key difference is when JavaScript checks the condition:
while (condition): Tests the condition before running the body. If initially false, the body runs zero times.do { ... } while (condition): Runs the body at least once first, then checks the condition at the bottom.flowchart TD
WStart["while loop"] --> WCond{"Condition true?"}
WCond -- "Yes" --> WBody["Run Body"] --> WCond
WCond -- "No" --> WDone["Exit Loop"]
while Loop ExampleUse while for retry counters, queue processing, or dividing numbers until a threshold is reached.
const jobQueue = ["resize-avatar", "send-receipt", "sync-index"];
while (jobQueue.length > 0) {
const nextJob = jobQueue.shift();
console.log("Processing job:", nextJob);
}
// do...while guarantees at least one execution
let attempt = 1;
do {
console.log(`Connection check attempt #${attempt}`);
attempt++;
} while (attempt <= 2);
while block moves the condition closer to false, the loop runs forever and freezes the process.while (true) without a clear exit: Always verify every branch inside a while (true) loop can reach a break or return.do...while (...): Always end do { ... } while (cond); cleanly with a semicolon.while instead of for?Pick for when looping over a numeric range or known list length, and pick while when looping until an external condition changes, like draining a queue or parsing tokens.
break and continue inside while and do...while?Yes, both keywords work identically in while, do...while, and for loops. Watch that continue inside while does not skip your counter update line!
continue skips the counter increment in a while loop?Jumping back to the while condition before incrementing your counter causes an infinite loop. Update counters before calling continue.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.