JS Loop While
JavaScript while and do...while Loops: Condition-Driven Iteration
The 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 Flow
The 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"]
Practical while Loop Example
Use 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);
Common Mistakes to Avoid
- Forgetting to update the condition variable: If nothing inside the
whileblock moves the condition closer tofalse, the loop runs forever and freezes the process. - Using
while (true)without a clear exit: Always verify every branch inside awhile (true)loop can reach abreakorreturn. - Missing the semicolon after
do...while (...): Always enddo { ... } while (cond);cleanly with a semicolon.
Frequently Asked Questions
When should I pick 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.
Can I use 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!
What happens if 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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.