What is the difference between a shallow copy and a deep copy?
The earlier questions in this topic covered how objects store values and how their keys are read. This answer explains what happens when you copy one of those objects, because copying sounds simple and behaves in a surprising way.
A shallow copy duplicates only the top level of the object. Every value inside it is still shared with the original, so a nested object stays the same object in both copies. A deep copy duplicates everything all the way down, so the two structures are completely separate and they never affect each other.
const original = {
name: 'Ada',
tags: ['a', 'b'],
nested: { count: 1 },
};
// A shallow copy.
const shallow = { ...original };
shallow.nested.count = 99;
console.log(original.nested.count); // 99 - the inner object is shared
console.log(original.tags.length); // 2
// A deep copy.
const deep = structuredClone(original);
deep.nested.count = 0;
deep.tags.push('c');
console.log(original.nested.count); // 99 - untouched
console.log(original.tags.length); // 2 - untouched
The shallow copy is the dangerous one, because it looks like it worked. Adding a new top-level property to the copy leaves the original alone, so a quick test passes. The moment you reach one level deeper and change a nested object or an array, both versions change together, and the bug then appears far away from the assignment that caused it.
There are three ways to make a shallow copy. You can use the spread operator inside an object literal, you can use the Object.assign method, or you can use the structuredClone function and only copy one level deep. They behave in the same way for plain data, and the spread syntax is the one to prefer because it reads more clearly.
Deep copies cost more and have more limits. The structuredClone function handles plain objects, arrays, dates, maps, sets, and circular references, but it cannot copy functions. It cannot turn a class instance into a plain object with its methods still working, and it throws when it meets a value that carries a function. For those cases you need a library such as the cloneDeep function from lodash, or you need to write your own recursive copy.