What is the difference between shallow and deep copy in JavaScript
· Category: JavaScript
Short answer
A shallow copy duplicates the top-level structure but shares nested references. A deep copy recursively clones all nested objects and arrays.
Key differences
| Aspect | Shallow copy | Deep copy |
|---|---|---|
| Top level | New object/array | New object/array |
| Nested objects | Shared references | Cloned recursively |
| Methods | Copied by reference | Copied by reference |
| Performance | Fast | Slower |
When to use each
- Use shallow copy with
...spreadorObject.assignwhen nesting is flat or immutability is not required. - Use deep copy when you need to modify nested data without affecting the original.
Example
const original = { a: 1, nested: { b: 2 } };
const shallow = { ...original };
shallow.nested.b = 3;
console.log(original.nested.b); // 3 (shared)
const deep = JSON.parse(JSON.stringify(original));
deep.nested.b = 4;
console.log(original.nested.b); // 3 (independent)
Why it matters
Mutating a shallow copy unexpectedly changes the source, causing state bugs. Use structuredClone for a modern, safe deep copy that handles more types than JSON.