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.
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.
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:
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:
0
1
2The 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
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.
let x = 10;
while (x < 5) {
console.log("This never prints");
}
// Nothing happens: 10 < 5 is false from the startCounting 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.
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:
Round 1
Round 2
Round 3
Round 4
Round 5This 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:
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:
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.78125You 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:
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:
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
| Pattern | Condition | Use Case |
|---|---|---|
| Counter | i < limit | Known iteration count (but for is cleaner) |
| Sentinel | value !== sentinel | Reading input until a stop marker |
| Threshold | value > minimum | Processing until a value is small enough |
| Flag | !done | Waiting for a state change |
| Retry | attempts < max && !success | Retrying a failed operation |
Avoiding Infinite Loops
The most common mistake with while loops is forgetting to change the condition inside the body.
// 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:
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
| while | for | |
|---|---|---|
| Setup | Manual, outside loop | Built into header |
| Condition check | Before each iteration | Before each iteration |
| Update | Manual, inside body | Built into header |
| Best for | Unknown iteration count | Known iteration count |
| Readability | Worse for counting | Better 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
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.
Frequently Asked Questions
When should I use a while loop instead of a for loop?
Can a while loop run zero times?
How do I stop an infinite while loop?
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.
More in this topic
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.
JS for Loop Syntax: A Complete Guide for Beginners
The for loop is the most common way to repeat code in JavaScript. Learn the three-part syntax, how each part works, and how to write clean, readable for loops.