Basic Web Development

Lesson 4 of 10

Savings Goal Counter

You save $15 a week for a $120 skateboard. A while loop counts the weeks for you.

What you will learn

  • while
  • The accumulator pattern
  • Counters
  • Stopping a loop
  • break
  • Input validation

Before you start

Times Table Grid. A `for` loop repeats a known number of times. A `while` loop repeats until something becomes true. You do not know the count in advance.

What this page does

  1. Type what you are saving for, what it costs, and how much you save each week.
  2. Click the button. The page tells you how many weeks it takes.
  3. It also lists your total after every week.
  4. Try typing 0 for the weekly amount. The page refuses. The next section explains why.

How it works

  • saved is the accumulator. It starts at 0 and grows every week.
  • weeks is the counter. It starts at 0 and adds 1 every week.
  • while (saved < goal) runs the loop body again and again. The loop stops as soon as the condition is no longer true.
let saved = 0;
let weeks = 0;

while (saved < goal) {
    saved = saved + perWeek;   // the accumulator grows
    weeks = weeks + 1;         // the counter grows
    log("Week " + weeks + ": $" + saved);
}

Build it step by step

  1. Make the page

    Make index.html with the three inputs, the button, an #answer paragraph, and a #log area. The controls appear, but nothing happens yet.

  2. Work it out on paper first

    Take a goal of 10 and a weekly amount of 4. Week 1 gives 4. Week 2 gives 8. Week 3 gives 12, which passes the goal, so you stop. You stopped when you reached the goal. That sentence is your while condition.

  3. Write the loop

    In the click handler, read the inputs and turn them into numbers. Then write the while loop with saved, weeks, and one log line per week. Test it with the numbers from step 2. The page should agree with your paper.

  4. See an infinite loop safely

    What happens if you forget the line saved = saved + perWeek? Write down your answer first. Do not delete the line, because that freezes the tab. Instead run the safe version at the bottom of savings.js in the console. It uses a safety counter and break to stop the loop after 1000 passes.

    let safety = 0;
    while (saved < goal) {
        // the line that grows "saved" is missing on purpose
        weeks = weeks + 1;
    
        safety = safety + 1;
        if (safety > 1000) {
            console.log("Stopped. This loop was never going to end.");
            break;
        }
    }
  5. Check the input

    Add an isNaN check so the page refuses text. Then add a check that refuses a weekly amount of 0 or less. That second check is the infinite loop from step 4, caught before it can start.

Try these changes

Make these in the files beside this guide. None of them need anything the lesson has not covered.

  • Add a $5 bonus every 4th week. Use `weeks % 4 === 0`.
  • Show how much money is still missing after each week.
  • Show the leftover money if the last week goes past the goal.
  • Try to write it with a `for` loop instead. It is awkward, because a `for` loop needs the number of weeks in advance, and that is the answer you are trying to find.
Teacher's versionHow to run this lesson, what to check, and any answers. Students do not need this.

How to teach it

  • Trace the loop on paper before writing any code. Ask "how did we know when to stop?" The student's own answer becomes the while condition.
  • Step 4 is the heart of the lesson. Ask the student to predict what happens with the missing line, and write the prediction down, before running anything.
  • Never delete the line for real. A frozen tab teaches nothing and costs five minutes. Use the safety-brake version in the console instead.
  • Connect the perWeek <= 0 check straight back to step 4. A weekly amount of zero is the same infinite loop in disguise. Say that out loud.