Lesson 2.1
Trace tables
6 min · 6 steps
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.
Step 2 of 6 · Trace the code
Fill in
iandtotalat 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)
Step 3 of 6 · Predict the result
Build a trace table for
aandb. 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]}[5, 8][3, 5][8, 13][2, 4]
Step 4 of 6 · Trace the code
A
whileloop gets a trace table too. Fill innanddigitsat the marked steps.function solution(n) { let digits = 0 while (n > 0) { n = Math.floor(n / 10) digits++ } return digits}solution(507)
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}013
Step 6 of 6 · Recap
- One column per variable, one row each time a value changes.
- Count the rounds from the loop condition.
k < 3from 0 means three rounds. - Try the smallest input too. A one-row trace can find a bug.