JavaScript while Loops

Repeat code while a condition is true, when you don't know how many times you need.

Lesson 15 of 56Beginner13 min read

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

JavaScript
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

JavaScript
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 for when you're counting or visiting every item in a list.
  • Use while when 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 while loop repeats as long as its condition is true.
  • The condition is checked before each lap, so the body may never run.
  • do...while always runs at least once, because it checks afterwards.
  • Something in the loop must make the condition false eventually.
  • Use for for counting and while for repeating until something changes.

JavaScript while Loop Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

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 🎲`);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 4Keep looping as long as we haven't rolled a 6.
  2. Line 5Roll the dice. This line is what eventually ends the loop.
  3. Line 6Count the attempts.
Example 2

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)}`);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 4The loop runs as long as we're below £1000.
  2. Line 5Grow by 25% each year.
  3. Line 6Count the years.
Example 3

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);
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 2 to 5The body runs once even though the condition is false after the first lap.
  2. Line 8A loop that relies on break to stop.
  3. Line 10Skip even numbers.
  4. Line 11Exit when we pass 7.

Common JavaScript while Loop Mistakes

Forgetting to update the condition

Don't
let count = 0;
while (count < 5) {
  console.log(count); // count never changes: infinite loop!
}
Do
let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}

Semicolon after while

Don't
while (i < 5); {
  i++;
}
Do
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.

Fill in the blankseasy

Count down from 3 to 1.

let n = 3;
 (n > 0) {
  console.log(n);
  n;
}
Predict the outputmedium

What does this print?

let x = 10;
while (x < 5) {
  console.log("inside");
}
console.log("done");
Multiple choicemedium

Which loop always runs its body at least once?

Fix the bugmedium

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);
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Steps: 7"
  • No errors

JavaScript while Loop Quiz

3 questions to check what you learned.

  1. When does a while loop stop?

    • When its condition becomes false (or on break)
    • After 10 laps
    • When the page reloads
    • Never
  2. 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
  3. 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.

  1. Use a while loop with guess starting at 1
  2. Stop when guess === secret
  3. Log Found 37 in 37 guesses (count guesses in tries)
const secret = 37;
let guess = 1;
let tries = 1;
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Found 37 in 37 guesses"
  • Uses a while loop