Skip to content
Trace code in your head

Lesson 2.1

Trace tables

6 min · 6 steps

  1. Step 1 of 6 · Explanation

    A trace table is how you run code in your head without losing track. One column per variable, one row per step.

    The rule is simple: write a new row every time a value changes. Don't skip steps, even when they feel obvious.

  2. Step 2 of 6 · Trace the code

    Fill in i and total at the marked steps. The values are the state before that line runs.

    function solution(n) {  let total = 0  for (let i = 1; i <= n; i++) {    total += i  }  return total}

    solution(3)

  3. Step 3 of 6 · Predict the result

    Build a trace table for a and b. What does it return?

    function solution(a, b) {  for (let k = 0; k < 3; k++) {    const t = a    a = b    b = t + b  }  return [a, b]}
    1. [5, 8]
    2. [3, 5]
    3. [8, 13]
    4. [2, 4]
  4. Step 4 of 6 · Trace the code

    A while loop gets a trace table too. Fill in n and digits at the marked steps.

    function solution(n) {  let digits = 0  while (n > 0) {    n = Math.floor(n / 10)    digits++  }  return digits}

    solution(507)

  5. Step 5 of 6 · Predict the result

    Same code. What does it return for n = 0?

    function solution(n) {  let digits = 0  while (n > 0) {    n = Math.floor(n / 10)    digits++  }  return digits}
    1. 0
    2. 1
    3. 3
  6. Step 6 of 6 · Recap

    • One column per variable, one row each time a value changes.
    • Count the rounds from the loop condition. k < 3 from 0 means three rounds.
    • Try the smallest input too. A one-row trace can find a bug.

    Pattern card

    Trace table
    When to use it: When you're not sure what a loop does. Pick a small input that still makes the loop run two or three times.
    // step | i | total//  1   | 1 |   0//  2   | 2 |   1//  3   | 3 |   3