What is a while loop?
Loops are one of the fundamental constructs that let us control the flow of a program. A while loop repeats a block of code while a specific condition is true. That makes while loops perfect for when you want to repeat code an unknown number of times.
You actually use while loops in everyday life all the time:
- While the road is straight, drive forward.
- While the temperature is at or below 68 degrees, keep the heat on.
In both examples, you don't know ahead of time when the road will curve or when the temperature will change. You just keep going until the condition stops being true. And in a video game: while the boss has health left, keep attacking!
A while loop in JavaScript looks like this:
while (booleanExpression) { // code to execute while // the condition is true }
Here is the whole trick in two sentences. If the boolean expression evaluates to true, the code inside the loop runs, then JavaScript jumps back up and checks the condition again. Once the condition evaluates to false, the computer exits the while loop and continues on with the rest of the program.
The check always comes first. The condition is tested before every single lap of the loop, including the very first one. Check, run the body, check, run the body... and the moment a check comes back false, the loop is over.
While loop vs. for loop
If you've met the for loop, you might wonder why JavaScript needs two kinds of loops. They both repeat code, but they answer different questions:
for loop
"Repeat this a known number of times."
- You know the count up front: for (let i = 0; i < 10; i++) means exactly 10 times
- Great for counting and visiting every item in an array or string
- The loop header updates the counter for you
while loop
"Repeat this until something changes."
- You don't know the count: it runs while a condition stays true
- Great for games, user input, and waiting for something to happen
- You are in charge of changing the condition variable inside the loop
Quick test: "Print hello 100 times" is a for loop job. "Keep attacking until the boss's health hits 0" is a while loop job, because you can't know how many hits it will take when every hit deals a random amount of damage!
Boss battle simulator
The best way to understand a while loop is to watch the computer re-check the condition on every lap. This boss fight is a while loop: every Attack runs exactly one lap. Watch the code panel: first the condition gets checked, then the body runs and the boss loses a random amount of health. When bossHP finally hits 0, the check comes back false and the loop ends in victory.
Now try the cursed sword. It deals 0 damage, so bossHP never changes, so the condition bossHP > 0 is true on every single check... forever. That's an infinite loop, and the simulator's safety brake will kick in before your browser melts.
Example: the taco countdown
Look at the example program below. In plain English, it says: while there are more than 0 tacos, eat a taco. Press Run, then explore with these guiding questions:
- What happens if you change the initial value of numTacos?
- What happens if you change the condition of the while loop to numTacos < 0?
- When does the final print statement run? Why does it run at that moment?
- What happens if you change the while loop to an if statement?
let numTacos = 5; while (numTacos > 0) { console.log("I ate 1 delicious taco!"); numTacos--; // Print out how many tacos are left console.log("There are " + numTacos + " tacos left."); } console.log("Looks like we need to make some more tacos!");
I ate 1 delicious taco! There are 4 tacos left. I ate 1 delicious taco! There are 3 tacos left. I ate 1 delicious taco! There are 2 tacos left. I ate 1 delicious taco! There are 1 tacos left. I ate 1 delicious taco! There are 0 tacos left. Looks like we need to make some more tacos!
The line that matters most: numTacos--; (which is shorthand for numTacos = numTacos - 1;). Every lap, the loop changes the variable in its own condition. That's what guarantees the condition eventually becomes false so the loop can end.
Looping on user input: the guessing game
Here's where while loops really shine. This guessing game keeps asking the player for a guess until they find the secret number. Nobody, not even the programmer, knows how many guesses it will take. A for loop can't do that!
Before running the program, predict what you think will happen. What is the while loop condition in plain English? When will the while loop end? (If the != symbol is new to you, it means "not equal to".)
let secretNum = Randomizer.nextInt(1, 10); let guess; while (guess != secretNum) { guess = readInt("Guess a number between 0 and 10: "); }
Guess a number between 0 and 10: 3 Guess a number between 0 and 10: 9 Guess a number between 0 and 10: 7
Notice the condition: guess != secretNum. In plain English, it says "keep looping while the guess is not the secret number." The player's correct guess is what finally flips the condition to false. A special value that ends a loop like this is often called a sentinel value: the loop stands guard until it shows up. This same pattern powers input validation, like re-asking for a password until it's correct.
Heads up: readInt and Randomizer.nextInt are CodeHS library commands. In a plain browser you'd write let guess = parseInt(prompt("Guess: ")); and Math.floor(Math.random() * 10) + 1 instead.
Why does the loop run at least once? The condition gets checked before the first lap, and guess starts out with no value (undefined). Since "no value" can never equal the secret number, the first check is guaranteed to be true, so the loop always asks for at least one guess.
Infinite loops
When writing a while loop, beware of the infinite loop! An infinite loop occurs when the condition is always true. When there is an infinite loop, the computer will attempt to run the while loop forever, which will ultimately result in crashing the browser or an error.
Let's revise our tacos program slightly. Look closely. Can you figure out why this program would result in an infinite loop?
let numTacos = 5; while (numTacos > 0) { console.log("There are " + numTacos + " tacos left."); }
There are 5 tacos left. There are 5 tacos left. There are 5 tacos left. There are 5 tacos left. There are 5 tacos left. There are 5 tacos left. ... this would repeat forever! (We stopped it for you.)
Spot the problem? We never change the value of numTacos inside the loop. That means numTacos will always be 5, which also means the condition numTacos > 0 will always be true. The computer repeats the loop an infinite number of times because the condition always evaluates to true and there is no way to exit the loop.
How to avoid it: a big warning sign is a loop body that never changes the variable in the condition. Before you run a while loop, ask yourself: "What line inside this loop moves the condition closer to false?" If you can't point to one, you probably have an infinite loop on your hands.
Want to feel it happen safely? Scroll back up to the boss battle simulator, equip the cursed sword, and watch the safety brake save you.
Practice: the chili dinner party
Serve the chili until it's gone
You are hosting a small dinner party and have made your famous chili. You've calculated that you have 15 scoops of chili and that each person will want between 1 and 4 scoops, depending on how hungry they are.
Write a program that keeps track of the number of chili scoops left as you serve your guests. Until there are no scoops left, ask a guest for the number of scoops they would like (you can use the readInt("prompt") command for this, or parseInt(prompt("...")) in a plain browser). After you serve each guest, update the number of chili scoops. When there are no scoops left, print out a statement informing your guests that there is no more chili left.
Here's the starter code:
// Create a variable to store the number of chili scoops // Write a while loop that keeps track of the amount of // chili as you serve each guest // Write a print statement to inform your guests that // the chili is gone.
// Create a variable to store the number of chili scoops let scoopsLeft = 15; // Serve guests while there is still chili left while (scoopsLeft > 0) { let scoops = readInt("How many scoops would you like? "); scoopsLeft = scoopsLeft - scoops; console.log("There are " + scoopsLeft + " scoops left."); } // Inform your guests that the chili is gone console.log("Sorry folks, there is no more chili left!");
How many scoops would you like? 4 There are 11 scoops left. How many scoops would you like? 2 There are 9 scoops left. How many scoops would you like? 3 There are 6 scoops left. How many scoops would you like? 4 There are 2 scoops left. How many scoops would you like? 2 There are 0 scoops left. Sorry folks, there is no more chili left!
The condition variable is scoopsLeft, and the line scoopsLeft = scoopsLeft - scoops; is what changes it each lap. This is an "unknown number of repeats" problem, so a while loop is the perfect tool: you can't know how many guests it takes to finish the pot. Bonus challenge: what happens if a guest asks for more scoops than you have left? How would you handle that?
Quick quiz
1. How many times does the body of this loop run?
let bossHP = 9; while (bossHP > 0) { console.log("Attack!"); bossHP = bossHP - 3; }
2. What causes an infinite loop?
3. Which task is the best fit for a while loop instead of a for loop?
Keep learning JavaScript
While loops repeat code as long as a condition is true. Next, review how for loops handle the "known number of times" jobs, or learn more about reading user input, the fuel that powers most while loops.