Shallow vs deep object copying
In short
| Copy type | What it does | Nested objects |
|---|---|---|
| Shallow copy | Copies only the top level of properties | References to the original objects are kept |
| Deep copy | Copies the entire tree (including nested objects) | Creates new copies of all nested structures |
Shallow copy example
javascript
const user = {
name: 'Tim',
address: { city: 'Kyiv' }
};
const clone = { ...user }; // shallow copy
clone.address.city = 'Lviv';
console.log(user.address.city); // "Lviv"Why this happened:
{ ...user }copies only the first level of properties;addressis an object, and the copy keeps the same reference to it;- changing
clone.address.cityaffected the original.
Deep copy example
javascript
const user = {
name: 'Tim',
address: { city: 'Kyiv' }
};
const clone = structuredClone(user); // deep copy
clone.address.city = 'Lviv';
console.log(user.address.city); // "Kyiv"Here a fully independent copy is created: all nested objects are copied anew too.
Illustration (a simple analogy)
Imagine:
javascript
user ──► address ──► { city: 'Kyiv' }
clone ─┘ ↑
└── (the same reference)In a shallow copy, both variables "point" to the same inner object.
With a deep copy:
javascript
user ──► address1 ─► { city: 'Kyiv' }
clone ─► address2 ─► { city: 'Lviv' }These are two fully independent objects.
How to make a deep copy
| Method | Deep copy | Notes |
|---|---|---|
structuredClone(obj) | Yes | Modern, preserves types |
JSON.parse(JSON.stringify(obj)) | Yes | Loses functions, Date, undefined |
_.cloneDeep(obj) (lodash) | Yes | The most reliable and cross-platform |
Summary
| Property | Shallow copy | Deep copy |
|---|---|---|
| Copies only the top level | Yes | No |
| Copies nested objects | No (references) | Yes |
| Changes to nested data affect the original | Yes | No |
| Examples | { ...obj }, Object.assign() | structuredClone(), _.cloneDeep() |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.