Suggest an editImprove this articleRefine the answer for “Copying through Object.assign”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)Copying with `Object.assign()` creates a **shallow copy**: this means **nested objects and arrays are copied by reference**, not by value. **Key point:** primitive properties are copied independently, while nested objects and arrays remain shared between the original and the copy.Shown above the full answer for quick recall.Answer (EN)Image## Short answer Copying with `Object.assign()` creates a **shallow copy**. This means **nested objects and arrays are copied by reference**, not by value. --- ## Example ```javascript const user = { name: 'Bohdan', address: { city: 'Kyiv', zip: 12345 } }; const clone = Object.assign({}, user); clone.address.city = 'Lviv'; console.log(user.address.city); // 'Lviv' ``` Why: - `Object.assign()` copies only the **first level of properties**; - the `address` property is an **object**, so a **reference** is copied; - changing the nested object (`city`) is reflected in the original. --- ## How this looks in memory ```javascript user.address ─────┐ │ (the same object) clone.address ────┘ ``` Both objects (`user` and `clone`) **reference the same** `address`. So a change inside `address` affects both. --- ## But! Primitive properties are copied normally ```javascript const user = { name: 'Bohdan', age: 25 }; const clone = Object.assign({}, user); clone.name = 'Oleh'; console.log(user.name); // "Bohdan" (independent) ``` Only **nested objects or arrays** stay shared. --- ## How to avoid this problem If you want to make a **deep copy**, use: ### `structuredClone()` (a built-in modern way) ```javascript const clone = structuredClone(user); clone.address.city = 'Lviv'; console.log(user.address.city); // "Kyiv" ``` ### `JSON.parse(JSON.stringify())` (universal, but with limitations) ```javascript const clone = JSON.parse(JSON.stringify(user)); ``` ### `_.cloneDeep()` from Lodash (reliable and compatible with all types) ```javascript import _ from 'lodash'; const clone = _.cloneDeep(user); ``` --- ## SUMMARY | What `Object.assign()` copies | Behavior | |---|---| | Primitive values (`string`, `number`, `boolean`) | copied by value | | Nested objects and arrays | copied **by reference** | | Functions | copied by reference | | Deep structures | not copied independently |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.