JavaScriptFundamental (ES6), part 1
Spread makes a shallow copy in JavaScript
27 Spread copies one level
fairCopy an object with { ...obj }, then write through the copy at the top level and at a nested level and report which writes leaked back into the source. Then make a copy that does not leak.
Stuck? Three hints, smallest first
- 1. Spread copies property values. For an object or array value, that value is a reference.
- 2. So
copy.owner === original.owner, and a write through either is visible from both. - 3.
structuredClonedoes a deep copy where it exists;JSON.parse(JSON.stringify(x))is the old fallback.
const deepCopy = (o) =>
typeof structuredClone === 'function' ? structuredClone(o) : JSON.parse(JSON.stringify(o));
const stall = { code: 'A1', owner: { name: 'Ngozi' }, tags: ['fabric'] };
const copy = { ...stall };
copy.code = 'A2'; // top level: private to the copy
copy.owner.name = 'Emeka'; // one level down: shared
copy.tags.push('lace'); // same story for an array
const rows = [{ qty: 1 }];
const rowsCopy = [...rows];
rowsCopy[0].qty = 99; // array spread is shallow too
const clone = deepCopy(stall);
clone.owner.name = 'Bola';
console.log('source code :', stall.code, '| copy:', copy.code);
console.log('shared owner :', stall.owner.name, copy.owner === stall.owner);
console.log('shared tags :', stall.tags);
console.log('array of rows :', rows[0].qty);
console.log('deep clone :', clone.owner.name, 'source still', stall.owner.name);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the copy is a different object at the top level', copy === stall, false);
test('so a top-level write stays in the copy', stall.code, 'A1');
test('but a nested object is the very same object', copy.owner === stall.owner, true);
test('so writing through the copy changes the source', stall.owner.name, 'Emeka');
test('and pushing to a nested array does the same', stall.tags, ['fabric', 'lace']);
test('array spread is shallow in exactly the same way', rows[0].qty, 99);
test('a deep copy gives a separate nested object', clone.owner === stall.owner, false);
test('so writing to the clone leaves the source alone', stall.owner.name, 'Emeka');
"Copy" in { ...obj } means copy the top row of key-value pairs. Every value that happens to be a reference is copied as a reference, so the two objects share everything below the first level. This is the single most common way that "immutable" state in a reducer turns out to be mutable.
structuredClone is the right deep copy now: it handles Map, Set, Date and cycles, and throws on a function. The JSON round trip silently drops functions and undefined, turns a Date into a string, and dies on a cycle — fine for plain data, wrong as a habit.