Skip to main content

Copying through Object.assign

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() copiesBehavior
Primitive values (string, number, boolean)copied by value
Nested objects and arrayscopied by reference
Functionscopied by reference
Deep structuresnot copied independently

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.