Suggest an editImprove this articleRefine the answer for “Shallow vs deep object copying”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**Shallow copy** copies only the top level of properties and keeps references to nested objects, while **deep copy** copies the entire tree, creating new copies of all nested structures. **Key point:** changing nested data in a shallow copy affects the original, while in a deep copy it does not.Shown above the full answer for quick recall.Answer (EN)Image## 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**; - `address` is an object, and the copy keeps **the same reference** to it; - changing `clone.address.city` affected 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()` |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.