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
└── cloneBoth 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 type | How 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 need | How to do it |
|---|---|
| A shallow copy | { ...obj } or Object.assign({}, obj) |
| A deep copy | structuredClone(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 = a | Explanation |
|---|---|
| Primitives (numbers, strings, etc.) | The value is copied |
| Objects, arrays, functions | The reference is copied, not the content |
| Changing the copy affects the original | Yes, if it is an object |
| How to avoid it | Use spread ({ ...obj }) or structuredClone() |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.