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.
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
- Open the Node.js Starter from the Home screen.
- The line inside the loop already ends with
//?, a Peek. - 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.
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.
Timeline · Esc to exit
Nothing in scope
everywhere
everywhere
in this loop
everywhere
in this loop
everywhere
in this loop
everywhere
in this loop
everywhere
everywhere
everywhere
everywhere
Find the Step that went wrong
- Step to the second pass of the loop. Variables shows
scoreis 7 andtotalis 12. - Press Next step.
totalis now 19: the 7 was added. - Press Esc or Esc, or Back to editing, to edit the code again.
- 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.