A for loop is ideal when you know how many times to repeat something. But what about "keep rolling the dice until you get a six" or "keep halving the number until it's below 1"? You can't know in advance how many laps those take. That's the job of the while loop.
while loops are less common than for loops in everyday web code, but they're the natural fit whenever the stopping point depends on something that happens during the loop: a random result, a value reaching a limit, or a task finishing.
The while loop
while (condition) {
// repeat this while the condition is true
}The condition is checked before every lap. If it's false at the very start, the body never runs at all.
Something inside the loop must eventually make the condition false. Usually that means changing a variable the condition depends on, such as adding to a counter or updating a total. If nothing changes, the loop runs forever.
The do...while loop
do {
// runs at least once
} while (condition);Here the condition is checked after each lap, so the body always runs at least once. That suits "try first, then check" situations, such as generating a random code and trying again if it's already taken.
break and continue in while loops
They work just as they do in for loops: break exits immediately, and continue jumps straight to the next condition check. A common pattern is while (true) { … if (done) break; }, which suits loops with several possible exit points. Use it carefully and make sure every path can reach the break.
while or for: which one?
Any for loop can be written as a while loop and the other way round, so the choice is about readability:
- Use
forwhen you're counting or visiting every item in a list. - Use
whilewhen you're waiting for something to change and can't predict how many laps it will take.
Picking the loop that matches the situation tells other readers what your code is meant to do.
JavaScript while Loop Syntax
while and do…while
let n = 0;
while (n < 3) {
n++;
}
do {
n--;
} while (n > 0);JavaScript while Loop Summary
- A
whileloop repeats as long as its condition is true. - The condition is checked before each lap, so the body may never run.
do...whilealways runs at least once, because it checks afterwards.- Something in the loop must make the condition false eventually.
- Use
forfor counting andwhilefor repeating until something changes.
JavaScript while Loop Examples
Each example runs in the page. Edit the code and press Run to see what changes.
Roll until you get a six
Run it a few times. The number of rolls changes each time.
let roll = 0;
let rolls = 0;
while (roll !== 6) {
roll = Math.floor(Math.random() * 6) + 1;
rolls++;
console.log("Rolled", roll);
}
console.log(`Got a six after ${rolls} rolls 🎲`);Line-by-line explanation
- Line 4Keep looping as long as we haven't rolled a 6.
- Line 5Roll the dice. This line is what eventually ends the loop.
- Line 6Count the attempts.
Doubling savings
How many years until £100 grows past £1000 if it grows 25% a year?
let savings = 100;
let years = 0;
while (savings < 1000) {
savings *= 1.25;
years++;
}
console.log(`After ${years} years: £${savings.toFixed(2)}`);Line-by-line explanation
- Line 4The loop runs as long as we're below £1000.
- Line 5Grow by 25% each year.
- Line 6Count the years.
do…while and while(true)
let attempts = 0;
do {
attempts++;
console.log("Attempt", attempts);
} while (attempts < 1);
let n = 0;
while (true) {
n++;
if (n % 2 === 0) continue;
if (n > 7) break;
console.log("Odd:", n);
}Line-by-line explanation
- Lines 2 to 5The body runs once even though the condition is false after the first lap.
- Line 8A loop that relies on
breakto stop. - Line 10Skip even numbers.
- Line 11Exit when we pass 7.
Common JavaScript while Loop Mistakes
Forgetting to update the condition
let count = 0;
while (count < 5) {
console.log(count); // count never changes: infinite loop!
}let count = 0;
while (count < 5) {
console.log(count);
count++;
}Semicolon after while
while (i < 5); {
i++;
}while (i < 5) {
i++;
}while (…); is an empty loop that never ends if the condition starts true.
JavaScript while Loop in Real Projects
When while is the right tool
Games run a "game loop" while the game isn't over. Programs retry network requests while they keep failing (up to a limit). Algorithms like binary search loop while the search range isn't empty. Reading data in chunks continues while there's more data.
JavaScript while Loop Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Count down from 3 to 1.
let n = 3;
(n > 0) {
console.log(n);
n;
}
What does this print?
let x = 10;
while (x < 5) {
console.log("inside");
}
console.log("done");Which loop always runs its body at least once?
This loop should halve the number until it's below 1 and log Steps: 7, but it never ends. Fix it.
let value = 100;
let steps = 0;
while (value >= 1) {
steps++;
}
console.log("Steps:", steps);- Logs "Steps: 7"
- No errors
value >= 1 become false?JavaScript while Loop Quiz
3 questions to check what you learned.
When does a while loop stop?
- When its condition becomes false (or on break)
- After 10 laps
- When the page reloads
- Never
When should you prefer while over for?
- When looping over an array
- Always
- When you don't know in advance how many laps you need
- Never, because while is outdated
What does
while (true) { … }need to avoid running forever?- continue
- A semicolon
- Nothing, because it stops automatically
- A break inside it
JavaScript while Loop Challenge
Guess the number
The computer "guesses" numbers counting up from 1 until it finds the secret.
- Use a
whileloop withguessstarting at1 - Stop when
guess === secret - Log
Found 37 in 37 guesses(count guesses intries)
const secret = 37;
let guess = 1;
let tries = 1;
- Logs "Found 37 in 37 guesses"
- Uses a while loop