Shallow Copy vs Deep Copy in JavaScript: Key Differences and Usage
shallow copy in JavaScript copies the top-level properties of an object but keeps references to nested objects, so changes in nested objects affect both copies. A deep copy duplicates all levels of an object, creating fully independent copies including nested objects, so changes do not affect the original.Quick Comparison
Here is a quick side-by-side comparison of shallow copy and deep copy in JavaScript.
| Factor | Shallow Copy | Deep Copy |
|---|---|---|
| Copy Depth | Copies only top-level properties | Copies all nested objects recursively |
| Nested Objects | References shared with original | Fully independent copies |
| Performance | Faster, less memory | Slower, more memory |
| Use Case | Simple objects or when nested changes are okay | Complex objects needing full independence |
| Common Methods | Object.assign(), spread operator {...obj} | structuredClone(), JSON methods, custom recursion |
Key Differences
A shallow copy duplicates only the first level of an object. This means if the object contains nested objects or arrays, the copy will hold references to the same nested objects as the original. So, if you change a nested object in the copy, it also changes in the original.
In contrast, a deep copy duplicates every level of the object, including all nested objects and arrays. This creates a completely independent clone. Changes in the copy do not affect the original at any level.
Shallow copies are faster and use less memory because they do not duplicate nested data. Deep copies are slower and use more memory but are safer when you want to avoid side effects from shared references.
Code Comparison
This example shows how to create a shallow copy of an object using the spread operator and how nested changes affect both original and copy.
const original = { name: 'Alice', address: { city: 'Wonderland' } }; const shallowCopy = { ...original }; shallowCopy.address.city = 'Looking Glass'; console.log(original.address.city);
Deep Copy Equivalent
This example shows how to create a deep copy using structuredClone() so nested changes do not affect the original.
const original = { name: 'Alice', address: { city: 'Wonderland' } }; const deepCopy = structuredClone(original); deepCopy.address.city = 'Looking Glass'; console.log(original.address.city);
When to Use Which
Choose shallow copy when you only need to duplicate the top-level properties and are okay with nested objects being shared. This is common for simple objects or when nested data is immutable.
Choose deep copy when you need a fully independent clone of an object, especially if you plan to modify nested objects without affecting the original. This is important in complex state management or when working with deeply nested data.