JavaScript While Loop Explained: A Complete Guide

A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.

5 min read

A while loop in JavaScript repeats a block of code for as long as a condition evaluates to true. It is the simplest loop type: one condition, one body, and it keeps going until the condition turns false.

Unlike a for loop, a while loop does not bundle initialization, condition, and update into one line. You manage the counter or state yourself, which gives you flexibility when the number of iterations is not known in advance.

While Loop Syntax

The syntax has two parts: the while keyword with a condition in parentheses, and a block of code in curly braces.

javascriptjavascript
while (condition) {
  // code to repeat
}

JavaScript evaluates the condition before every iteration. If the condition is true, the body runs, then JavaScript checks the condition again.

This repeats until the condition is false, at which point the loop exits and code after the loop continues.

Here is the smallest working example:

javascriptjavascript
let i = 0;
 
while (i < 3) {
  console.log(i);
  i++;
}

The condition is checked before every pass, so the body runs while i is 0, 1, and 2, then stops as soon as i reaches 3. Output:

texttext
0
1
2

The loop runs three times. On the fourth check, i equals 3 and 3 < 3 is false, so the loop stops. The key detail is i++ inside the body -- without it, the condition would never change, and the loop would run forever.

How the Condition Is Evaluated

While loop execution flow

The condition is checked first, before the body runs even once. If the condition starts false, the body never executes. This is what separates while from do while -- a while loop can run zero times.

javascriptjavascript
let x = 10;
 
while (x < 5) {
  console.log("This never prints");
}
// Nothing happens: 10 < 5 is false from the start

Counting with a While Loop

The most basic while loop pattern uses a counter variable, just like a for loop. The difference is that the counter setup, condition, and update are spread across the code instead of packed into one line.

javascriptjavascript
let counter = 1;
 
while (counter <= 5) {
  console.log(`Round ${counter}`);
  counter++;
}

Each pass logs the current round and then increases the counter, so the loop keeps going while it stays at or below 5. Output:

texttext
Round 1
Round 2
Round 3
Round 4
Round 5

This produces the same result as a for loop would. When the count is known, a for loop is usually more readable because all three parts are together. Use while for counting only when the update step depends on something inside the loop body that would be awkward to express in a for header.

Looping Until a Condition Changes

The real strength of while is when you do not know the iteration count ahead of time. The loop runs until some external or computed state says stop.

A common pattern is dividing a number until it is small enough:

javascriptjavascript
let value = 100;
let steps = 0;
 
while (value > 1) {
  value = value / 2;
  steps++;
  console.log(`Step ${steps}: ${value}`);
}

Each pass cuts the value in half and counts the step, so the loop keeps dividing until the value drops to 1 or below. Output:

texttext
Step 1: 50
Step 2: 25
Step 3: 12.5
Step 4: 6.25
Step 5: 3.125
Step 6: 1.5625
Step 7: 0.78125

You could not write this with a simple for loop because you would need to compute the number of steps in advance. The while loop naturally stops when the value drops below the threshold.

Waiting for External State

Another strong use case for while is polling or waiting for something outside the loop to change. In real applications, this often involves asynchronous code, but the pattern is the same:

javascriptjavascript
let ready = false;
let attempts = 0;
 
while (!ready && attempts < 5) {
  console.log(`Attempt ${attempts + 1}: checking...`);
  attempts++;
  if (attempts === 3) ready = true;
}
 
console.log(ready ? "Ready!" : "Timed out");

In real code, an event or callback would flip ready to true. Here a counter simulates that, and the loop stops once ready is true or five attempts pass. Output:

texttext
Attempt 1: checking...
Attempt 2: checking...
Attempt 3: checking...
Ready!

The loop exits early when ready becomes true, or after five attempts if it never does. The exact iteration count depends on when the condition changes, not on a predetermined number.

Common While Loop Patterns

PatternConditionUse Case
Counteri < limitKnown iteration count (but for is cleaner)
Sentinelvalue !== sentinelReading input until a stop marker
Thresholdvalue > minimumProcessing until a value is small enough
Flag!doneWaiting for a state change
Retryattempts < max && !successRetrying a failed operation

Avoiding Infinite Loops

The most common mistake with while loops is forgetting to change the condition inside the body.

javascriptjavascript
// DANGEROUS: x never changes
let x = 0;
while (x < 10) {
  console.log(x);
  // Missing: x++
}

This loop prints 0 forever because x stays 0 and the condition 0 < 10 is always true. Always verify that at least one statement inside the loop body moves the condition toward false. For a complete guide, see how to avoid infinite loops in JavaScript.

Another common trap is using the wrong comparison operator:

javascriptjavascript
let y = 0;
while (y !== 5) {
  y += 2; // y goes: 0, 2, 4, 6, 8... never equals 5
}

Since y jumps by 2, it skips right over 5. The condition y !== 5 is always true, so the loop runs forever. Use <= or < instead when the increments can overshoot.

While vs For: A Quick Comparison

whilefor
SetupManual, outside loopBuilt into header
Condition checkBefore each iterationBefore each iteration
UpdateManual, inside bodyBuilt into header
Best forUnknown iteration countKnown iteration count
ReadabilityWorse for countingBetter for counting

For an overview of all loop types and how to choose, see the JavaScript loops tutorial. If you need the body to run at least once regardless of the condition, reach for the do while loop instead.

Rune AI

Rune AI

Key Insights

  • A while loop repeats its body as long as the condition is true.
  • The condition is checked before every iteration, including the first.
  • Use while when the number of iterations is unknown ahead of time.
  • Always ensure the condition eventually becomes false.
  • The while condition can depend on external state, not just a counter.
RunePowered by Rune AI

Frequently Asked Questions

When should I use a while loop instead of a for loop?

Use a while loop when you do not know how many times the loop needs to run in advance. For example, reading data until it runs out, waiting for user input, or retrying a failed network request. If you know the exact count, a for loop is cleaner.

Can a while loop run zero times?

Yes. If the condition is false the first time it is checked, the loop body never runs. If you need the body to run at least once, use a do while loop instead.

How do I stop an infinite while loop?

Make sure the loop body changes a variable that the condition depends on. Without that change, the condition stays true forever. In a browser, you can close the tab. In Node.js, press Ctrl+C.

Conclusion

The while loop is the simplest loop in JavaScript: one condition, one body, repeat until false. It is the right tool when you do not know the iteration count in advance and need a condition-driven loop that may run zero times.