DocsHub
Loops

While Loop

Learn how to use the while loop to repeat code when you don't know exactly how many times it should run.

While Loop

The for loop is great when you know exactly how many times to repeat something. But sometimes you don't know that upfront — you just want to keep going until something changes.

That's what the while loop is for.

A while loop repeats a block of code as long as a condition is true. It doesn't care about counting — it only cares about that condition.

while (condition) {
  // runs as long as condition is true
}

Think of it like this — a for loop says "repeat this 10 times". A while loop says "keep going until I tell you to stop."


How It Works

true false Start Is condition true? Run code block Update something Exit loop

The condition is checked before every iteration. If it's true — run the block. If it's false — stop immediately. If it's false from the very beginning, the block never runs at all.


Basic Example

let count = 1;

while (count <= 5) {
  console.log(count);
  count++;
}
// 1
// 2
// 3
// 4
// 5

Let's trace what happens here step by step:

count = 1 → 1 <= 5 → true  → prints 1 → count becomes 2
count = 2 → 2 <= 5 → true  → prints 2 → count becomes 3
count = 3 → 3 <= 5 → true  → prints 3 → count becomes 4
count = 4 → 4 <= 5 → true  → prints 4 → count becomes 5
count = 5 → 5 <= 5 → true  → prints 5 → count becomes 6
count = 6 → 6 <= 5 → false → loop exits

Notice that the update (count++) lives inside the loop body — not in the parentheses like a for loop. You are responsible for moving things forward yourself.


When to Use while Over for

The best use of a while loop is when the number of iterations depends on something happening — not on a fixed count.

Waiting for correct user input

let password = "";

while (password !== "open123") {
  password = prompt("Enter password:");
}

console.log("Access granted!");

You have no idea how many attempts the user will take. Could be 1, could be 10. The loop just keeps going until they get it right. A for loop would be the wrong tool here — you don't have a number to count to.

Processing data until it runs out

let stock = 50;
let orders = 0;

while (stock > 0) {
  stock -= 10;  // each order uses 10 units
  orders++;
}

console.log(`Processed ${orders} orders until stock ran out.`);
// Processed 5 orders until stock ran out.

You don't know upfront how many orders will fit — you just keep processing until stock hits zero. The condition drives the loop, not a counter.


The Condition Can Be Anything Truthy

Just like if statements, the while condition accepts any truthy or falsy value — not just comparisons.

let items = ["apple", "mango", "grape"];

while (items.length) {
  let removed = items.pop();
  console.log(`Removed: ${removed}`);
}

// Removed: grape
// Removed: mango
// Removed: apple

items.length starts at 3 — truthy. After each pop() it decreases. When it hits 0 — falsy — the loop stops. Clean and readable with no counter needed.


Infinite Loop — The Biggest Danger

If the condition never becomes false, the loop runs forever. This freezes the browser tab or crashes Node.js.

// ❌ Infinite loop — count never changes
let count = 1;

while (count <= 5) {
  console.log(count);
  // forgot count++ — count stays 1 forever
}

This is the most common while loop mistake. Always make sure something inside the loop moves you toward the condition becoming false.

If your browser tab freezes while practicing — you probably have an infinite loop running. Close the tab and check your loop condition and update.


while vs for — Choosing the Right One

Both loops can technically do the same job. The choice is about clarity — which one makes your intention more obvious to someone reading the code.

// You know the count — use for
for (let i = 0; i < 10; i++) {
  console.log(i);
}

// You don't know the count — use while
while (!isConnected) {
  tryReconnecting();
}
SituationUse
Repeating a fixed number of timesfor
Looping through an array by indexfor
Repeating until something changeswhile
Waiting for an event or conditionwhile
Number of iterations is unknownwhile

A Real Example — Countdown Timer

let seconds = 10;

while (seconds > 0) {
  console.log(`Launching in ${seconds}...`);
  seconds--;
}

console.log("🚀 Launch!");

// Launching in 10...
// Launching in 9...
// ...
// Launching in 1...
// 🚀 Launch!

seconds starts at 10 and decreases every iteration. When it hits 0, the condition seconds > 0 becomes false and the loop exits — then the launch message prints.


Summary

  • The while loop repeats as long as a condition is true
  • The condition is checked before every iteration
  • Use it when the number of repetitions is unknown upfront
  • Always update something inside the loop — otherwise it runs forever
  • Use for when you have a fixed count, use while when you have a condition to watch

On this page