Skip to main content

Why can't you copy an object with the = operator?

Short answer

The = operator does not copy an object, it only copies the reference to it in memory. That is, both names (variables) will point at the same object.


Example

javascript
const user = { name: 'Tim' }; const clone = user; // "copy" the object clone.name = 'Oleh'; console.log(user.name); // 'Oleh' console.log(clone.name); // 'Oleh'

Changing clone also changed user, because it is the same object in memory.


What this looks like "under the hood"

javascript
Memory: ┌────────────┐ { name: 'Tim' }└──────┬─────┘ ├── user └── clone

Both user and clone are references to the same object. When you write const clone = user, another reference is created, not a new copy.


Why this happens

JavaScript has two data types:

Data typeHow it is copied
Primitives (number, string, boolean, null, undefined, symbol, bigint)by value
Reference types (object, array, function, Map, Set, etc.)by reference
javascript
let a = 5; let b = a; b = 10; console.log(a); // 5 (a copy of the value) const obj1 = { x: 1 }; const obj2 = obj1; obj2.x = 2; console.log(obj1.x); // 2 (a reference)

If you actually need a copy

Use one of these approaches:

What you needHow to do it
A shallow copy{ ...obj } or Object.assign({}, obj)
A deep copystructuredClone(obj) or _.cloneDeep(obj)

Example:

javascript
const user = { name: 'Tim' }; const clone = { ...user }; // creates a new object clone.name = 'Oleh'; console.log(user.name); // "Tim" console.log(clone.name); // "Oleh"

Now the objects are independent.


Summary

What happens with const b = aExplanation
Primitives (numbers, strings, etc.)The value is copied
Objects, arrays, functionsThe reference is copied, not the content
Changing the copy affects the originalYes, if it is an object
How to avoid itUse spread ({ ...obj }) or structuredClone()

Short Answer

Interview ready
Premium

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