While Loop
Imagine you are filling a bucket with water from a tap. 🪣
You don't count how many mugs of water to pour. You simply keep pouring while the bucket is not full. The moment it is full, you stop.
In the last lesson, we learned the for loop, which is great when you know how many times to repeat something, like "print 10 times."
But sometimes you don't know the number of repeats in advance. You just want to keep going until something happens. For this, JavaScript gives us the while loop.
What Is a While Loop?
A while loop repeats a block of code again and again, as long as a condition is true.
It keeps asking one question before every round: "Is the condition still true?"
- Yes → run the code again.
- No → stop the loop.
Syntax
while (condition) {
// code to repeat
}
Unlike the for loop, the while loop has only one part inside the brackets: the condition.
So where do the starting value and the update go?
- Starting value → created before the loop
- Update → written inside the loop
Your First While Loop
How It Works, Step by Step
| Step | Value of count | Condition count <= 5 | Action |
|---|---|---|---|
| Round 1 | 1 | ✅ true | Print, then count++ |
| Round 2 | 2 | ✅ true | Print, then count++ |
| Round 3 | 3 | ✅ true | Print, then count++ |
| Round 4 | 4 | ✅ true | Print, then count++ |
| Round 5 | 5 | ✅ true | Print, then count++ |
| Check | 6 | ❌ false | Loop stops |
The flow:
Check condition → true → Run code → Check condition → true → Run code → ...
↓ (false)
Exit the loop
Key points:
- The condition is checked before every round.
- If the condition is false from the very start, the loop never runs, not even once:
Real-Life Examples
The while loop shines when the number of rounds depends on a situation.
Example 1: Saving money for a new phone 📱
You save ₹2,000 every month. How many months will it take to buy a phone worth ₹15,000?
Output:
You can buy the phone after 8 months!
Total saved: ₹16000
We didn't know it would take 8 months. The loop figured it out for us!
Example 2: Mobile battery charging 🔋
Example 3: Counting the digits in a number
Example 4: Reversing a number
Example 5: Tea shop orders ☕
Serve customers until the milk runs out.
Looping Through an Array with While
You can also go through an array using a while loop.
Tip: For arrays, the for loop is usually cleaner, because all three parts are in one line. Use
whilewhen the stopping point is not fixed.
Infinite Loops ⚠️
This is the most common mistake with while loops.
If you forget to update the variable, the condition stays true forever, and the loop never ends. This can freeze your browser!
let i = 1;
while (i <= 5) {
console.log(i);
// ❌ forgot i++ → prints 1 forever!
}
Another example:
let i = 10;
while (i > 0) {
console.log(i);
i++; // ❌ wrong direction → i keeps growing, it never reaches 0
}
How to avoid infinite loops:
- ✅ Always update the variable inside the loop.
- ✅ Make sure the update moves toward making the condition false.
- ✅ Before running, ask yourself: "When will this loop stop?"
If your browser freezes: Close the tab. In Node.js, press Ctrl + C to stop the program.
Intentional infinite loops with break
Sometimes developers write while (true) on purpose and stop it using break when a condition is met.
We will learn more about break in the Break & Continue lesson.
For Loop vs While Loop
Both loops can do the same work. The difference is when to use which.
| Point | For Loop | While Loop |
|---|---|---|
| Best when | You know how many times to repeat | You don't know how many times |
| Parts in brackets | 3 (start; condition; update) | 1 (condition only) |
| Start value | Inside the brackets | Before the loop |
| Update | Inside the brackets | Inside the loop body |
| Example | Print a table from 1 to 10 | Keep saving until you reach the goal |
The same task, written both ways:
Simple way to remember:
- "Do this 10 times" →
forloop - "Keep doing this until..." →
whileloop
Common Mistakes to Avoid
| Mistake | Problem | Fix |
|---|---|---|
Forgetting the update (i++) | Infinite loop | Always update the variable inside the loop |
| Updating in the wrong direction | Infinite loop | Counting up → ++, counting down → -- |
Putting a semicolon after while (...) | The loop body never runs properly | Remove the ; |
| Creating the variable inside the loop | It resets every round → infinite loop | Create it before the loop |
Example of the last mistake:
while (i <= 5) {
let i = 1; // ❌ resets to 1 every time
i++;
}
Quick Summary Table
| Concept | Example |
|---|---|
| Basic while loop | while (i <= 5) { ... i++; } |
| Loop until a goal | while (savings < target) { ... } |
| Loop through an array | while (i < arr.length) { ... i++; } |
| Intentional infinite loop | while (true) { if (...) break; } |
Key Takeaways
- A while loop repeats code as long as the condition is true.
- It is best when you don't know in advance how many times the loop should run.
- Create the starting value before the loop and update it inside the loop.
- If the condition is false at the start, the loop doesn't run at all.
- Always make sure the loop can stop. Forgetting the update creates an infinite loop.