Complete JavaScript Course Module 4: Beginner: Loops

while and do...while Loops

  • Beginner
  • Lesson 4.2
  • 4 min read
  • 15 of 76 in the course

In short

A JavaScript while loop repeats code as long as a condition is true, and a do...while loop always runs at least once. Learn when to use each one. What is a while loop? A for loop is perfect when you know how many times to repeat something. But sometimes you do not know.

A JavaScript while loop repeats code as long as a condition is true, and a do...while loop always runs at least once. Learn when to use each one.

What is a while loop?

A for loop is perfect when you know how many times to repeat something. But sometimes you do not know. Imagine filling a glass of water: you keep pouring while the glass is not full. You do not count how many seconds it takes.

A while loop has only a condition. It checks the condition, runs the code if it is true, then checks again.

let savings = 0;
let weeks = 0;

while (savings < 100) {
  savings += 15;
  weeks++;
}

console.log(`You reached $${savings} after ${weeks} weeks.`);
// Output: You reached $105 after 7 weeks.

Here we save $15 every week until we have at least $100. We did not know the number of weeks in advance, so while fits well. Inside the loop, savings += 15 changes the value that the condition checks. Without that line, the loop would never end.

Common mistake: Forgetting to change the variable inside a while loop. A for loop has a step built in, but a while loop does not. You must update the value yourself, or you create an infinite loop.

Counting with a while loop

You can rebuild any for loop as a while loop. The three parts are just in different places:

let i = 1;            // start

while (i <= 3) {      // condition
  console.log(`Ticket ${i}`);
  i++;                // step
}
// Output:
// Ticket 1
// Ticket 2
// Ticket 3

It works, but for simple counting the for loop is shorter and keeps everything in one line. Use a while loop when the number of repeats depends on something that happens inside the loop.

What is a do...while loop?

A do...while loop runs the code first and checks the condition after. This means the code always runs at least once, even if the condition is false from the start.

let number = 10;

do {
  console.log(`The number is ${number}`);
  number++;
} while (number < 5);
// Output: The number is 10

The condition 10 < 5 is false, but the message still prints once, because the check happens at the end. A normal while loop with the same condition would print nothing. Notice the semicolon after while (number < 5);, which is needed in a do...while loop.

Example: keep asking until the answer is valid

The classic use for do...while is asking a user for input. You must ask at least once, and you keep asking until the answer is good. Paste this into your browser console:

let age;

do {
  const answer = prompt("How old are you? (enter a number)");
  age = Number(answer);
} while (Number.isNaN(age) || age <= 0);

console.log(`Thanks! You are ${age} years old.`);
// If you type "abc", then "-3", then "25":
// Output: Thanks! You are 25 years old.

Let's go line by line. prompt() shows a small pop-up box and returns what the user typed as a string. Number(answer) converts it into a number, as you saw in the type conversion lesson. If the user types letters, the result is NaN ("Not a Number"). The condition says: keep asking while the age is not a number or is zero or less. When the user finally types a good number, the condition becomes false and the loop ends.

Note: If the user clicks "Cancel", prompt() returns null, and Number(null) is 0, so the loop asks again. Real websites use form fields instead of prompt(), which you will learn in the DOM module.

Which loop should I use?

LoopChecks the conditionBest for
forBefore each roundA known number of repeats, counting, going through a list
whileBefore each roundRepeating until something changes, number of repeats unknown
do...whileAfter each roundCode that must run at least once, like asking for input

Tip: When you are unsure, start with a for loop. If you find yourself struggling to fit the problem into a counter, switch to while.

Practice exercise

A ball is dropped from 100 meters. Each bounce reaches half the height of the previous one. Use a while loop to print the height of each bounce until the height is below 1 meter, and count how many bounces there were.

Hint: Start with let height = 100; and let bounces = 0;. Inside the loop, divide height by 2 and add 1 to bounces. The condition is height >= 1.

Key takeaways

  • A while loop repeats as long as its condition is true and checks before each round.
  • A do...while loop checks after each round, so it always runs at least once.
  • In both loops, you must change something inside the loop so it can end.
  • Use for when you know the count, while when you do not, and do...while when the code must run first.