The while Loop
Repeat code as long as a condition stays true.
Syntax
while (condition) { ... }The while loop repeats as long as its condition is true. Use it when you do not know in advance how many times you will loop.
Avoid infinite loops
Make sure something inside the loop eventually makes the condition false, or it will run forever.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Keep reading data from a paginated API until the response signals there are no more pages.
- Retry a failed network request up to a maximum number of attempts while it keeps failing.
- Process items from a queue until the queue is empty in a background task worker.
More examples
Basic while loop
Executes the body repeatedly as long as count is less than 5, incrementing each time.
let count = 0;
while (count < 5) {
console.log("count:", count);
count++;
}do-while guarantees one run
Uses do-while so the body runs at least once before checking the exit condition.
let input;
do {
input = "yes"; // simulates user providing valid input
} while (input !== "yes");
console.log("Valid input received:", input);Drain a queue with while
Dequeues and processes each task until the array is empty, a common pattern for job queues.
const queue = ["task1", "task2", "task3"];
while (queue.length > 0) {
const task = queue.shift();
console.log("Processing:", task);
}
console.log("Queue empty");
Discussion