When working with objects and arrays in JavaScript, you often need to copy data. But not all copies are the same! There are two types:
- Shallow Copy
- Deep Copy
Let’s understand what they mean, with easy examples.
What is a Shallow Copy?
A shallow copy copies only the first level of an object or array.
If the object has nested objects, it does not create a full new copy.
Instead, it just copies the reference (address) to the nested objects.
Example:
const original = {
name: 'Ali',
address: {
city: 'Tehran'
}
};
// Shallow copy using spread operator
const shallow1 = { ...original };
// Or using Object.assign
const shallow2 = Object.assign({}, original);
// Change in shallow copy
shallow1.address.city = 'Shiraz';
console.log(original.address.city); // Output: 'Shiraz'
Why?
Because both shallow1.address
and original.address
point to the same inner object.
What is a Deep Copy?
A deep copy copies everything, including all nested objects.
It creates a full, independent copy. Changing one object will not affect the other.
Example:
const original = {
name: 'Ali',
address: {
city: 'Tehran'
}
};
const deep = JSON.parse(JSON.stringify(original));
// Change in deep copy
deep.address.city = 'Isfahan';
console.log(original.address.city); // Output: 'Tehran'
Why?
Because deep
and original
are fully separated. No shared parts.
How to Create Copies
✅ Shallow Copy Methods
For objects:
const copy1 = { ...original };
const copy2 = Object.assign({}, original);
For arrays:
const copy1 = [...originalArray];
const copy2 = originalArray.slice();
✅ Deep Copy Methods
- Using JSON (easy but limited):
const deepCopy = JSON.parse(JSON.stringify(obj));
⚠️ This will remove functions, Dates, undefined, Map, Set, etc.
-
Using
structuredClone()
(modern and accurate):
const deepCopy = structuredClone(obj);
✅ Works in modern browsers and supports many data types.
- Using Lodash (library):
import cloneDeep from 'lodash/cloneDeep';
const deepCopy = cloneDeep(obj);
Final Thoughts
- Use shallow copy when your object is simple and doesn’t have inner objects.
- Use deep copy when you want full independence between the copy and original.