Skip to content

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.

JavaScript
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
valueAdded?total after
3yes3
1no3
4yes7

The number printed is 7. The middle row matters: skipping an update is still an iteration.

Practice and check

Guided practice

Practice, not scored

Use the values [2, 3, 3] instead. Which list gives total after each iteration, in order?

Choose one answer

Exit check

Counts toward completion

A loop starts with total = 1 and adds each even number in [2, 5, 4]. What is the final total?

Choose one answer

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