JavaScript while Loop
Table of Contents + −
In the previous lesson, we learned how to repeat code a set number of times with a for loop. Now let’s meet the while loop, which keeps running as long as a condition stays true.
🔁 What is a while Loop?
A while loop runs a block of code over and over for as long as its condition is true. Before each pass, JavaScript checks the condition. If it is true, the loop runs the block once more. If it is false, the loop stops.
Here is the basic syntax:
while (condition) { // code that runs while the condition is true}The condition goes inside the parentheses, and the code we want to repeat goes inside the curly braces. As long as the condition evaluates to true, the block runs again.
🔢 Counting Up to 5
Let’s count from 1 up to 5 using a while loop.
let count = 1;
while (count <= 5) { console.log(count); count++; // update the condition variable}// 1// 2// 3// 4// 5Let’s walk through what happens line by line:
let count = 1creates the variable we will track, starting at1.while (count <= 5)checks the condition before each pass; while it is true, the block runs.console.log(count)prints the current value on each pass.count++adds one tocount, moving it closer to the stopping point.
This repeats until count becomes 6. At that point count <= 5 is false, so the loop stops.
| Part | Role |
let count = 1 | Sets up the variable before the loop starts |
count <= 5 | The condition that is checked before each pass |
console.log(count) | The work the loop does on each pass |
count++ | Updates the variable so the loop can eventually stop |
🤔 When to Use while Instead of for
A for loop is the right choice when we know how many times we want to repeat. A while loop shines when we do not know the number of passes ahead of time and only want to keep going until some condition is met.
A simple rule of thumb
Use a for loop when you can count the repetitions in advance. Use a while
loop when you repeat until something happens, such as reaching a total or
running out of items.
💰 Saving Until We Reach a Target
Let’s say Alex saves $20 each week and wants to know how many weeks it takes to reach $100. We do not know the answer in advance, so a while loop fits perfectly.
let savings = 0;let weeks = 0;
while (savings < 100) { savings += 20; // add this week's deposit weeks++; // count the week}
console.log(`It took ${weeks} weeks to reach $${savings}.`);// It took 5 weeks to reach $100.Let’s step through this loop:
let savings = 0andlet weeks = 0set our running total and week counter to zero before the loop starts.while (savings < 100)keeps the loop running untilsavingsreaches the target.savings += 20adds this week’s deposit on each pass.weeks++counts the week so we know how long it took.console.log(...)prints the result once the loop ends.
Because we let the loop decide when to stop, we did not have to figure out the number of weeks ourselves.
♾️ Always Update the Condition Variable
The most important rule of a while loop is that something inside the block must change the condition so it eventually becomes false. If the condition never changes, the loop runs forever. This is called an infinite loop, and it will freeze the program.
// ❌ Wrong - count never changes, so this runs foreverlet count = 1;while (count <= 5) { console.log(count);}
// ✅ Correct - count grows each pass, so the loop endslet n = 1;while (n <= 5) { console.log(n); n++;}Let’s compare the two versions:
- In the first loop,
countstays at1forever because nothing updates it, socount <= 5is always true and the loop never stops. - In the second loop,
n++increasesnon every pass, soneventually reaches6, the condition becomes false, and the loop ends.
The only difference is that one line that updates the variable.
Watch out for infinite loops
If your program seems frozen, check that the variable in your condition is
actually being updated inside the loop. A missing n++ is the usual cause.
⚠️ Common Mistakes to Avoid
| Mistake | Problem | Solution |
| Forgetting to update the variable | The condition stays true and the loop runs forever | Change the variable inside the block, such as count++ |
| A condition that never becomes false | The loop never stops | Make sure the update moves the variable toward the stopping point |
| Off-by-one error | The loop runs one time too many or too few | Check whether you need < or <= for the count you want |
🔧 Try It Yourself!
- Write a
whileloop that prints the numbers from 1 to 10. - Write a loop that starts at 10 and counts down to 1 using
--. - Add $15 to a
savingsvariable in a loop until it reaches at least $90, then print how many passes it took. - Remove the variable update from one of your loops, predict what happens, then add it back.
🧩 What You’ve Learned
- ✅ A
whileloop repeats code as long as its condition is true - ✅ The syntax is
while (condition) { ... } - ✅ Use
whilewhen you do not know the number of passes ahead of time - ✅ Something inside the block must update the condition variable
- ✅ Forgetting that update creates an infinite loop that freezes the program
🚀 What’s Next?
Next we will learn a loop that always runs at least once before checking its condition. Let’s continue to do while Loop.