Debugging & reference tracing

Debug an unexpected shared update

Lesson 19 of 20 · 13 min · Module 6: Design, validate & debug

A function can return the right-looking value and still change data elsewhere. Follow references and test the original input after the call.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Trace object identity across a function call
  • Use failing tests to isolate a side effect

The idea

The starter aliases its input and then edits its records. Repair it so every output record is a separate object while leaving the caller’s array and objects untouched.

const record = { completed: false };
const alias = record;
alias.completed = true;
console.log(record.completed);

01Write the promise before editing code

The function promises both completed output and unchanged input. A test that checks only the output misses half of that promise.

02Follow each reference

updated and sessions initially refer to the same array. Even replacing the first line with [...sessions] leaves the contained objects shared.

03Repair one ownership level at a time

Use map for the array and spread for each record. Then run checks for the output, the old values, and distinct identities.

Your turn

Fix completeAll(sessions). Return a new array with a new copy of every session and completed set to true. Preserve all other fields, and do not modify the input.

What the checks look for

  • Completes every returned record and preserves fields
  • Does not mutate input records or reuse their identities
  • Produces a new empty array for empty input
Try it in the editor →

Take this with you

A debugging session improves when you can name the exact behavior that must stay true.

Go a little further

Add an input record with an extra notes field and verify it survives the transformation.

Learn JavaScript Foundations for free

20 short lessons with real code and instant checks.

See the whole course →