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
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.
// Makes an editable copy of a user for the "edit profile" form.
function editableCopy(user) {
return { ...user };
}Read it, then pick a line.
The name survives a cancel but the city doesn’t. What’s different about where they live in the object?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
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
- Reproduce both cases from the report: change the name on the copy (the original is fine), change the city (the original changes).
- The difference is depth:
nameis a top-level field,cityis insideaddress. Spread only copies one level. - Confirm it:
copy.address === user.addressistrue.
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()andcopy.copyare shallow;copy.deepcopyisn’t.