The while Loop

Repeat code as long as a condition stays true.

Syntaxwhile (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

Try it yourself
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.

Example · js
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.

Example · js
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.

Example · js
const queue = ["task1", "task2", "task3"];
while (queue.length > 0) {
  const task = queue.shift();
  console.log("Processing:", task);
}
console.log("Queue empty");

Discussion

  • Be the first to comment on this lesson.
The while Loop — JavaScript | SoundsCode