L03 Loops and running state
16 minSuggested first: L02 Branches and comparisons
Outcome
Build a small trace table that tracks an accumulator across loop iterations.
Learn
A loop repeats a block. A for...of loop visits the values of an array in order. An
accumulator is a variable that carries a running result from one iteration to the next.
Write down its value before the first iteration, then one row per iteration, including the ones
where it doesn't change. Python's for value in values: expresses the same pattern.
Worked example
Predict the number printed after the loop. Start with total = 0 and add one row per value.
let total = 0;
for (const value of [3, 1, 4]) {
if (value >= 3) total += value;
}
console.log(total);
Predict first, then show the worked explanation
value | Added? | total after |
|---|---|---|
| 3 | yes | 3 |
| 1 | no | 3 |
| 4 | yes | 7 |
The number printed is 7. The middle row matters: skipping an update is still an iteration.
Practice and check
Common mistake
Resetting the accumulator each iteration. Point to the line where it's initialized and ask how often that line runs: once, before the loop.
Next
Module review. Before the next lesson, go back to the branches lesson's exit check and change
it: set n to 3 and the condition to n >= 3. Which branch runs now, and why is equality the
case that matters?
References
- JavaScript Guide (MDN)
- The Python Tutorial (Python documentation)