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.

Beside the line, 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+→
  • Previous step: ⌘← or Ctrl+←
  • 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 buttons are at the top right, the menus are in theMenu button at the left end of the tabs, and shortcuts use Ctrl where a Mac uses ⌘. The rest works the same way.

Esc

Type to search every docs page.

JSpark is downloading

When you open JSpark-Setup.exe, Windows may stop it once, because the installer isn’t code-signed yet. If the file came from jspark.app:

A blue Windows box, “Windows protected your PC”: Microsoft Defender SmartScreen prevented an unrecognised app from starting. Under it, the link More info, and the button Don’t run.

1Click More info.

The same box after More info: Application JSpark-Setup-1.4.0.exe, Publisher Unknown publisher, and the buttons Run anyway and Don’t run.

2Then click Run anyway.

You see this only once: updates install inside the app. More in Install JSpark.