#15 · Shared references

Find the bug · #15 · Shared references Medium JavaScript

Cancelling an edit still changes the address

The edit-profile form works on a copy, but cancelling a change to the city still saves it.

On this page

The report

Bug report

The edit-profile form works on a copy of the user. Changing the name and cancelling works fine, but changing the city and cancelling still changes the saved address.

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
// Makes an editable copy of a user for the "edit profile" form.
function editableCopy(user) {
  return { ...user };
}

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 user = { name: 'Asha', address: { city: 'Pune' } };
const copy = editableCopy(user);
copy.name = 'Asha R';
copy.address.city = 'Delhi';
console.log(user.name, user.address.city);

It prints

Asha Delhi

It should print

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

The bug (line 3)

Line 3 spreads the user into a new object. That’s a shallow copy: the top-level fields are copied, but address is still the same object in both. Changing copy.name is safe; changing copy.address.city changes the original. A deep copy (structuredClone) copies the nested objects too.

The fix

1// Makes an editable copy of a user for the "edit profile" form.2function editableCopy(user) {3  return { ...user };3  return structuredClone(user);4}

How you’d find it

  1. Reproduce both cases from the report: change the name on the copy (the original is fine), change the city (the original changes).
  2. The difference is depth: name is a top-level field, city is inside address. Spread only copies one level.
  3. Confirm it: copy.address === user.address is true.

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 user = { name: 'Asha', address: { city: 'Pune', pin: '411001' } };
const copy = editableCopy(user);
copy.address.pin = '110001';
assert.equal(user.address.pin, '411001');
assert.deepEqual(copy.address, { city: 'Pune', pin: '110001' });

Where else this bites

  • Object.assign({}, obj) and [...array] are shallow too.
  • Python’s dict.copy() and copy.copy are shallow; copy.deepcopy isn’t.
Your progress stays on this device.