MenuGuides / Find why a loop gives the wrong answer

Docs / Guides

Find why a loop gives the wrong answer

Peek at the value a loop gives, then replay it one Step at a time to see where it went wrong.

On this page

This guide uses the loop in the Node.js Starter's demo. It adds up four scores. Say you wanted only the scores of 10 or more, so you expected 42.

const scores = [12, 7, 30, 4]

let total = 0
for (const score of scores) {
  total += score
}

Peek at the result

  1. Open the Node.js Starter from the Home screen.
  2. The line inside the loop already ends with //?, a Peek.
  3. Wait for the Run, or press ⌘↵ or Ctrl+Enter.

The value appears beside the line: 53, not 42. The loop added something it should not have.

The Peek shows 53, the value from the loop's last pass.

A Peek shows the value from the last pass only. To see every pass, replay the loop in the Timeline. More about Peeks: Peek.

Open the Timeline

Press ⌘⇧↵ or Ctrl+Shift+Enter, or choose Run → Timeline. JSpark runs the Snippet again and records every Step. The code is read-only while the Timeline is open.

The Timeline works with Node Snippets only, not with web pages. See Step Run and the Timeline.

Watch the values change

Move through the Steps one at a time:

  • Next step: ⌘→ or Ctrl+Right
  • Previous step: ⌘← or Ctrl+Left
  • Play and Pause: Space or Space

The lit line is the Step on screen. The Variables panel lists every value at that Step, grouped by scope: score under in this loop, total under everywhere. A value the Step changed is marked. See Moving through Steps and Variables.

Step by Step, total goes 0, 12, 19, 49, and the Peek follows it.

Find the Step that went wrong

  1. Step to the second pass of the loop. Variables shows score is 7 and total is 12.
  2. Press Next step. total is now 19: the 7 was added.
  3. Press Esc or Esc, or Back to editing, to edit the code again.
  4. Fix the line so it adds only the scores you want:
for (const score of scores) {
  if (score >= 10) total += score
}

Run it again. The console now prints total 42.

The pictures show JSpark on a Mac. On Windows, the window looks a little different and uses Ctrl for ⌘, but everything works the same way.

Esc

Type to search every docs page.