Repeat Code With while

Picture a guessing game where the player has to find a secret code. They type a number, the program says whether it’s too low or too high, and then it asks again. And again. Maybe the player gets it on the first try, or maybe it takes nine. Your program can’t know in advance, so it needs a way to repeat the same steps until the job is done.

That’s what loops are for, and this course is all about them. By the end, you’ll build a small secret code guessing game that runs in your terminal, checks every answer, asks again when an answer doesn’t make sense, and finishes cleanly when the player wins or types quit.

How This Course Works

This course assumes you can write functions that return a value, make decisions with if and else, compare values, turn text into a number with Number(), read a string’s characters by position, and check whether a value is usable. You also know how to save a script in VS Code and run it with node in the integrated terminal, opened in your course folder.

If you came straight here without the earlier JavaScript Basics courses, that’s okay! As long as those skills feel familiar, you can follow along. Loops are new, so you’ll start from the very first one.

In text lessons like this one, you’ll run short scripts on your own computer and change them to see what happens. In on-site coding exercises, you’ll write code in your browser and get feedback from automated tests. You’ll also step through loops in an interactive widget and watch a short video.

The game comes at the end, after you’ve learned to repeat code, plan a program, and ask questions in the terminal. You’ll build it in small, runnable steps.

Start From One Checked Guess

Warm up with something you already know. Here’s a function that checks one guess against a secret number up to 10. Save it as check_guess.js in your course folder:

Language: JavaScript Filename: check_guess.js
function checkGuess(guess, secret) {
  if (guess > 10) {
    return "Pick a number up to 10";
  }
  if (guess === secret) {
    return "You got it!";
  }
  if (guess < secret) {
    return "Too low";
  }
  return "Too high";
}

console.log(checkGuess(12, 7));
console.log(checkGuess(4, 7));
console.log(checkGuess(7, 7));

Before you run it, predict the three lines it prints. The first if rejects a guess above 10, and each return ends the function, so only one message comes back per call. Now run the script and compare:

Language: Shell
$ node check_guess.js
Pick a number up to 10
Too low
You got it!

If your prediction matched, your function and branch skills are ready for this course. Notice the limit, though. Each guess needed its own handwritten call. A real player decides how many guesses they need, so you can’t write the right number of calls ahead of time.

Repeat Code While a Condition Is True

A while loop runs a block of code again and again, as long as a condition is true. You’ll start with a countdown, because you can see every step of it in the output. Save this as countdown.js:

Language: JavaScript Filename: countdown.js
let seconds = 3;

while (seconds > 0) {
  console.log(seconds);
  seconds = seconds - 1;
}

console.log("Liftoff!");

Give it a spin in your terminal:

Language: Shell
$ node countdown.js
3
2
1
Liftoff!

Three lines came from inside the loop and one from after it. Each part of the program has a job:

  • The start: Line 1 gives seconds its first value before the loop begins.
  • The condition: seconds > 0 in line 3 decides whether the loop runs another time.
  • The body: The code between the curly braces runs once on every pass through the loop.
  • The update: Line 5 changes seconds, so the condition can eventually become false.

The order matters. JavaScript checks the condition at the top, before every pass. When it’s true, the whole body runs, and then JavaScript goes back to the top to check again. When it’s false, JavaScript skips the body and continues with the first line after the closing brace, which prints Liftoff!.

Try two changes. Set seconds to 5 and run the script again. Then set it to 0 and predict what you’ll see before you run it. With 0, the very first check is already false, so the body never runs and you only see Liftoff!. A while loop can run zero times.

Trace the Passes With a Table

When a loop changes two values, a small table helps you keep track. Say you planted a sunflower that’s 12 cm tall and grows 9 cm each week. How many weeks until it reaches at least 50 cm? Save this as sunflower.js:

Language: JavaScript Filename: sunflower.js
let height = 12;
let weeks = 0;

while (height < 50) {
  height = height + 9;
  weeks = weeks + 1;
}

console.log("After", weeks, "weeks:", height, "cm");

Before you run it, follow the loop pass by pass. Each row starts with the check at the top, then shows the values after the body has run or marks where the loop ends:

Check height < 50 height after the pass weeks after the pass
12 < 50 is true 21 1
21 < 50 is true 30 2
30 < 50 is true 39 3
39 < 50 is true 48 4
48 < 50 is true 57 5
57 < 50 is false loop ends loop ends

Watch the last row. The loop stops because 57 fails the check, so the values after the loop are the ones from the final pass: 57 cm after 5 weeks. Run the script to confirm:

Language: Shell
$ node sunflower.js
After 5 weeks: 57 cm

When a loop ends because its condition is false, its variables keep their values from that final check. Here, that’s the first height of at least 50 cm. Later in the course, you’ll meet a way to leave a loop early, before its condition turns false.

Now trace one yourself. Change the first line to let height = 25;. Before you run the script, fill in a table like the one above, including the check that fails. How many passes does the loop make, and what does it print?

Check height < 50 height after the pass weeks after the pass
25 < 50 is true 34 1
34 < 50 is true 43 2
43 < 50 is true 52 3
52 < 50 is false loop ends loop ends

That’s three passes, and the script prints After 3 weeks: 52 cm. If your count is off by one, check that your last row is the failed check.

Want to practice on a fresh loop? The mentor shows you one, asks for your prediction, and then checks it with you.

Stop a Loop That Never Ends

The update line moves a loop toward its end. To see what happens without it, save a copy of your countdown as countdown_forever.js, reset seconds to 3, and delete the line seconds = seconds - 1;:

Language: JavaScript Filename: countdown_forever.js
let seconds = 3;

while (seconds > 0) {
  console.log(seconds);
}

console.log("Liftoff!");

Nothing in the body changes seconds now, so seconds > 0 stays true forever. This is an infinite loop. It keeps printing 3 until you stop it, and Liftoff! never prints.

To stop a running script, click in the terminal and press Ctrl+C, even on macOS, where it’s Ctrl and not Cmd. Now run node countdown_forever.js, let a column of 3 values pile up for a second, and press Ctrl+C. Check that your prompt comes back. Nothing is broken.

When a loop doesn’t end, ask two questions. Which variable does the condition check? Which line in the body changes that variable, and does the change move the condition toward false? An update in the wrong direction, such as seconds = seconds + 1, also keeps the loop running forever.

To compare the update lines, step through your countdown in the widget below. Pick how many passes you expect, then press Step to move through the start, the check, the body, and the update one part at a time. Change the start value of seconds or the update line, predict again, and step again:

Interactive diagram — enable JavaScript to view.

With seconds starting at 3 and an update of seconds - 1, you should have seen three passes, a fourth check of 0 > 0 that’s false, and seconds holding 0 after the loop. With a start of 0, the first check is already false, so the body never runs. With the update deleted or set to seconds + 1, the check comes back true on every pass, so Liftoff! never prints.

Ready to hunt for a missing update? The mentor gives you a broken loop and hints until you spot the fix.

Write Your Own Loop

Now write a loop from scratch. Picture a very patient player in your guessing game who tries 1, then 2, then 3, and so on, until they hit the secret code. Write patient_guesser.js so that it prints each wrong guess and then the code it finds. Use 4 as the secret code.

You’ll need a start for the guess, a condition that’s true as long as the guess isn’t the secret, and an update that moves to the next number. Before you run your version, predict how many lines it prints and what guess holds after the loop. Here’s one way to write it:

Language: JavaScript Filename: patient_guesser.js
const secret = 4;
let guess = 1;

while (guess !== secret) {
  console.log(guess, "is not the code");
  guess = guess + 1;
}

console.log("Found it:", guess);

The condition uses !==, so the loop keeps going until the guess equals the secret. Your output should match this:

Language: Shell
$ node patient_guesser.js
1 is not the code
2 is not the code
3 is not the code
Found it: 4

Three wrong guesses print, and guess is 4 after the loop, because 4 !== 4 is the first check that’s false. Now change the secret to 1 and predict the output. Then try 0. With 0, the guess starts above the secret and only grows, so it never matches. Press Ctrl+C. You’ve just found an infinite loop by reasoning about the update.

Run the Body First With do…while

A while loop checks before the first pass, which is usually what you want. Sometimes, though, the body has to run once before there’s anything to check. For example, you can check an answer only after you’ve asked the question once. For that, JavaScript has the do...while loop, which runs the body first and checks the condition afterward.

Compare it with your countdown, starting from 0. Save this as countdown_do.js:

Language: JavaScript Filename: countdown_do.js
let seconds = 0;

do {
  console.log(seconds);
  seconds = seconds - 1;
} while (seconds > 0);

console.log("Liftoff!");

Run it and look at the first line:

Language: Shell
$ node countdown_do.js
0
Liftoff!

The plain while version printed only Liftoff! when seconds started at 0. This version prints 0 first, because the body runs before the first check. Then -1 > 0 is false, and the loop ends. Notice the semicolon after while (seconds > 0).

Reach for do...while only when the body must run at least once. Otherwise, a while loop is the clearer choice, and it’s the one you’ll use most in this course. For the full syntax, see MDN’s pages on while and do...while.

Try choosing for yourself. Which loop fits each task, and why?

  1. Count down a kitchen timer whose seconds might already be at 0.
  2. Ask the player for a guess, and ask again as long as the guess is wrong.

The timer needs while. If it’s already at 0, zero passes is the right answer, and only a check at the top allows that. The guessing task fits do...while, because there’s nothing to check until you’ve asked once, so the body must run first. Later in this course, you’ll meet a third shape for this job, while (true) with break, which suits a game that can end in more than one way.

Check What You Can Do Now

You can now read a while loop as a start, a condition, a body, and an update. You can predict how many passes it makes and what its variables hold afterward, and you can stop one that never ends. Test yourself with one last prediction: if the sunflower started at 50 cm, how many weeks would the loop count, and why?

It counts zero weeks, because 50 < 50 is false at the very first check. If you got that, then you’re ready to write a loop on your own.

In the next lesson, Count the Years to a Savings Target, you’ll do just that in this course’s first coding exercise. You’ll put a while loop inside a function that returns how many years it takes to reach a savings goal. You’ll write and run the code in your browser, and automated tests will tell you which cases work and which need attention.

Run your code early and often, and read any error message for clues. The exercise page explains its controls before you start.

Become a Member to join the conversation.