Shallow vs deep copy of an array in JavaScript
Intermediate · 4 min read
Copying an array looks easy: [...xs] and you're done. For a list of numbers or strings, that really is a full copy. But put an array or an object inside the list, and the copy shares that inner piece with the original. Change it through the copy, and the original changes too.
In this tutorial you will see that happen, learn why, and then make copies that go all the way down. You will also compare the two common ways to do a deep copy, structuredClone and a JSON round trip, and see what each one does to dates, undefined and functions. You should know arrays, objects and the spread syntax ....
References, in one paragraph
A variable that holds an array or an object doesn't hold the thing itself. It holds a reference, something like an address that points to where the thing lives. An array of arrays is a list of addresses. Copying that list copies the addresses, so both lists point at the same inner arrays.
const inner = [1, 2];
const a = [inner];
const b = [...a];
console.log(a === b); // false: two outer arrays
console.log(a[0] === b[0]); // true: one inner array, shared
Shallow and deep
A shallow copy makes a new outer array but reuses everything inside it. Spread, slice() and concat() all make shallow copies. They copy exactly one level.
A deep copy also copies every array and object inside, and everything inside those, all the way down. Nothing is shared, so the copy and the original are fully independent.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
44 A copy that is only one level deep
fairCopy an array with spread, then change something inside a nested element and check the original. Then make a copy where that does not happen.
Stuck? Three hints, smallest first
- 1. Spread,
sliceandconcatall copy exactly one level. - 2.
structuredClonecopies all the way down, includingDate,MapandSet. - 3. A JSON round trip is deep too, and it changes your data on the way through.
Step 1: a spread copy
Start with an array that holds three different kinds of thing: an inner array, an object and a date.
const original = [[1, 2], { seats: 9 }, new Date('2024-03-01')];
const shallow = [...original];
console.log(shallow !== original); // true
So far it looks like a real copy. shallow is a different array from original.
Step 2: change something inside the copy
const original = [[1, 2], { seats: 9 }, new Date('2024-03-01')];
const shallow = [...original];
shallow[0].push(3);
console.log(original[0]); // [ 1, 2, 3 ]
We only touched shallow, yet the 3 shows up in original. shallow[0] and original[0] are the same inner array, as the References section showed. This is the bug that appears the day someone nests the data: the code worked for flat lists and breaks for nested ones.
Step 3: a deep copy with structuredClone
structuredClone is built into modern browsers and Node. It copies a value all the way down.
const original = [[1, 2], { seats: 9 }, new Date('2024-03-01')];
const deep = structuredClone(original);
deep[0].push(99);
console.log(deep[0]); // [ 1, 2, 99 ]
console.log(original[0]); // [ 1, 2 ]
console.log(deep[2] instanceof Date); // true
Now the change stays in the copy. instanceof Date checks whether a value is a date, and the cloned date still is one. structuredClone also knows how to copy Map and Set.
Step 4: the JSON round trip
An older trick, still common, is to turn the value into JSON text and parse it back. The result is deep too, because parsing builds every array and object from scratch. But JSON only knows strings, numbers, booleans, null, arrays and plain objects, so anything else gets changed on the way through:
const original = [[1, 2], { seats: 9 }, new Date('2024-03-01')];
const viaJson = JSON.parse(JSON.stringify(original));
console.log(viaJson[0]); // [ 1, 2 ]
console.log(typeof viaJson[2]); // string
console.log(viaJson[2]); // 2024-03-01T00:00:00.000Z
console.log(JSON.parse(JSON.stringify([{ a: undefined }]))); // [ {} ]
The date came back as a piece of text, so calling getFullYear() on it would now throw an error. And the property a, which held undefined, disappeared, because JSON has no way to write undefined.
Step 5: what structuredClone refuses
Some things can't be cloned at all. A function is one of them. Instead of quietly dropping it, structuredClone throws an error named DataCloneError:
const clonedFunction = (() => {
try { structuredClone([() => 1]); return 'cloned'; } catch (e) { return e.name; }
})();
console.log(clonedFunction); // DataCloneError
try runs the code, and if it throws, catch receives the error so we can read its name. A loud error is better than missing data you only notice later.
The full solution
The panel makes all three copies of the same array, changes the shallow and the deep copy, and prints what the JSON round trip did to the date and to undefined. Press Run and read the notes.
const original = [[1, 2], { seats: 9 }, new Date('2024-03-01')];
const shallow = [...original];
shallow[0].push(3); // reaches into the original
const deep = structuredClone(original);
deep[0].push(99); // does not
const viaJson = JSON.parse(JSON.stringify(original));
const clonedFunction = (() => {
try { structuredClone([() => 1]); return 'cloned'; } catch (e) { return e.name; }
})();
console.log('the copy is a new array :', shallow !== original);
console.log('but the inner array is not:', original[0], '<- the 3 arrived here too');
console.log('structuredClone :', deep[0], ' original still', original[0]);
console.log('--- what JSON does on the way through ---');
console.log('the Date became :', typeof viaJson[2], JSON.stringify(viaJson[2]).slice(0, 12) + '...');
console.log('structuredClone kept it :', deep[2] instanceof Date);
console.log('undefined inside an object:', JSON.parse(JSON.stringify([{ a: undefined }])));
console.log('cloning a function :', clonedFunction);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a spread copy is a different array', shallow !== original, true);
test('but the nested array is shared, so the original changed', original[0], [1, 2, 3]);
test('structuredClone reaches all the way down, so the clone changed alone', deep[0], [1, 2, 3, 99]);
test('leaving the original as it was', original[0], [1, 2, 3]);
test('a JSON round trip is deep as well', viaJson[0], [1, 2, 3]);
test('but it turns a Date into a string', typeof viaJson[2], 'string');
test('while structuredClone keeps it a Date', deep[2] instanceof Date, true);
test('and JSON silently drops an undefined property', JSON.parse(JSON.stringify([{ a: undefined }])), [{}]);
test('structuredClone refuses a function instead of dropping it', clonedFunction, 'DataCloneError');
Also Basic 34, which clones an object. The array version has the same shape and one extra sting: [...xs] looks like a complete copy, and for a list of numbers or strings it is. Add one nested array or record and half the copy is shared, so a change "to the copy" edits the original — a bug that appears the day someone nests the data.
Three tools, three failure modes. Spread is shallow. A JSON round trip is deep but lossy: dates become strings, undefined properties disappear, NaN becomes null, and a cycle throws. structuredClone handles dates, maps, sets and cycles, and refuses functions with a DataCloneError — refusing loudly is better than dropping quietly.
Common mistakes
- Calling
[...xs]a full copy. It copies one level. Any nested array or object is still shared with the original. - Using the JSON round trip on dates. Dates turn into strings, and
undefinedproperties vanish without a warning. - Cloning data that holds functions.
structuredClonethrows aDataCloneError. Keep functions out of the data you copy.
Try it yourself
- Use
slice()instead of spread in Step 2 and check that the 3 still reaches the original. - Put a
Mapin the array, clone it withstructuredClone, and check that the copy is still aMap. - Find out what a JSON round trip does to
[NaN].