Codiqo

Learn JavaScript · lesson 22 of 60 · about 8 minutes

Tracing Loops

Hand out a badge for every full week of the streak: trace a loop lap by lap, and catch the off-by-one errors that hide at the edges.

What you'll learn

  • Trace variables lap by lap
  • Spot off-by-one errors
  • Use console.log to debug

Weekly badges

Sam wants to reward streaks: a 🏅 badge on day 7, another on day 14, and so on, each showing the day it was earned. A visitor on day 20 gets 🏅7 🏅14. Getting the edges right is the hard part: does day 7 itself earn a badge? Tracing the loop lap by lap answers questions like that before a visitor finds the bug.

Trace tables

A trace table follows each variable through every lap. For this loop:

let t = 0; for (let i = 1; i <= 3; i++) { t += i * 2; }

| Lap | i | t after |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 2 | 6 |
| 3 | 3 | 12 |

Checking the trace

let t = 0;
for (let i = 1; i <= 3; i++) {
  t += i * 2;
  console.log(`i=${i} t=${t}`);
}

Output

i=1 t=2
i=2 t=6
i=3 t=12

Step through it: badges for a 15-day streak

const theirDays = 15;
let badges = "";
for (let d = 7; d <= theirDays; d += 7) {
  badges += ` 🏅${d}`;
}
console.log(`Badges:${badges}`);

Output

Badges: 🏅7 🏅14

Off-by-one errors

The most common loop bug is running one lap too many or too few. Check the first and last values: is it < or <=? Does it start at 0 or 1?

Tip

Dropping a console.log inside a loop is the quickest way to see what's really happening.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.