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

StepValue of countCondition count <= 5Action
Round 11✅ truePrint, then count++
Round 22✅ truePrint, then count++
Round 33✅ truePrint, then count++
Round 44✅ truePrint, then count++
Round 55✅ truePrint, then count++
Check6❌ falseLoop 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 while when 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.

PointFor LoopWhile Loop
Best whenYou know how many times to repeatYou don't know how many times
Parts in brackets3 (start; condition; update)1 (condition only)
Start valueInside the bracketsBefore the loop
UpdateInside the bracketsInside the loop body
ExamplePrint a table from 1 to 10Keep saving until you reach the goal

The same task, written both ways:

Simple way to remember:

  • "Do this 10 times" → for loop
  • "Keep doing this until..." → while loop

Common Mistakes to Avoid

MistakeProblemFix
Forgetting the update (i++)Infinite loopAlways update the variable inside the loop
Updating in the wrong directionInfinite loopCounting up → ++, counting down → --
Putting a semicolon after while (...)The loop body never runs properlyRemove the ;
Creating the variable inside the loopIt resets every round → infinite loopCreate it before the loop

Example of the last mistake:

while (i <= 5) {
  let i = 1;   // ❌ resets to 1 every time
  i++;
}

Quick Summary Table

ConceptExample
Basic while loopwhile (i <= 5) { ... i++; }
Loop until a goalwhile (savings < target) { ... }
Loop through an arraywhile (i < arr.length) { ... i++; }
Intentional infinite loopwhile (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.