What is the difference between shallow and deep copy in JavaScript
· Category: JavaScript
Short answer
A shallow copy duplicates the top-level object but shares nested references. A deep copy recursively duplicates all nested objects and arrays, creating fully independent clones.
Details
Spread syntax ({ ...obj }) and Object.assign create shallow copies. If obj contains an array, both copies point to the same array. For deep copies, modern browsers support structuredClone(obj), which handles dates, maps, sets, and circular references safely. The older JSON.parse(JSON.stringify(obj)) technique loses functions, undefined, and special object types.
Understanding copying is essential when passing state around. For safer state updates in complex applications, see how to destructure objects and arrays to extract values before copying. You might also want to learn about what are JavaScript Proxy and Reflect objects for advanced object behavior control.
Tips
- Prefer
structuredClonefor deep copying whenever browser support allows. - For immutable updates in frameworks like React, shallow copies combined with spread are usually sufficient.
- To verify what you are copying, check out how to check data types in JavaScript accurately before performing clone operations.