#13 · Shared references

Find the bug · #13 · Shared references Easy JavaScript

Cancel doesn’t cancel

Users change a setting, press Cancel, and the change sticks anyway.

On this page

The report

Bug report

On the settings screen, users change the theme and then press Cancel. The change sticks anyway, as if they’d pressed Save.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaScriptClick the line you think is wrong
// Opens a copy of the settings to edit; Cancel throws the copy away.
function startEditing(settings) {
  const draft = settings;
  return draft;
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
const saved = { theme: 'light', fontSize: 16 };
const draft = startEditing(saved);
draft.theme = 'dark';
console.log(saved.theme);

It prints

dark

It should print

light
Show the answer: the bug, the fix, and how you’d find it

The bug (line 3)

Line 3 assigns the settings object to draft. That copies the reference, not the object: both names point to the same settings, so editing the draft edits the saved settings, and Cancel has nothing to throw away. Make a real copy: { ...settings }.

The fix

1// Opens a copy of the settings to edit; Cancel throws the copy away.2function startEditing(settings) {3  const draft = settings;3  const draft = { ...settings };4  return draft;5}

How you’d find it

  1. Reproduce: start editing, change the draft’s theme, then look at the saved settings. They changed too.
  2. A value that changes “by itself” usually means two names for one object. Check where the draft comes from: const draft = settings.
  3. Confirm it: draft === saved is true. They’re the same object.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

const saved = { theme: 'light', fontSize: 16 };
const draft = startEditing(saved);
draft.fontSize = 20;
assert.equal(saved.fontSize, 16);
assert.deepEqual(draft, { theme: 'light', fontSize: 20 });

Where else this bites

  • React state updated by mutating the same object: the screen doesn’t re-render.
  • In Python, draft = settings is the same; use dict(settings) or copy.deepcopy.
Your progress stays on this device.