Sub topic 10
Objects as References: Shallow and Deep Copies
This chapter assumes you can create object literals, read and write properties, and list them with Object.keys or Object.entries. It explains why changing one object can unexpectedly change another, and how to make copies that stay independent.
Variables Hold References, Not Objects
A primitive value such as a number or string is stored directly in its variable. An object is different. The variable holds a reference, which is a pointer to the object somewhere in memory. Assigning that variable to another variable copies the reference. The object itself is not copied.
const a = { count: 1 };
const b = a;
b.count = 2;
console.log(a.count); // 2
console.log(a === b); // trueBoth a and b point to the same object, so a write through either one is visible through the other. Equality works the same way. === compares references, so two objects with identical contents are still unequal:
console.log({ x: 1 } === { x: 1 }); // falseThe same rule applies to function arguments. A function that receives an object can change the caller's object, because it receives a copy of the reference.
Shallow Copies
A shallow copy is a new object whose top-level properties are copied from the original. Spread syntax and Object.assign both make shallow copies. They copy own enumerable properties, which are the same ones Object.keys lists.
const original = { name: "Ada", tags: ["math"] };
const shallow = { ...original };
shallow.name = "Grace";
console.log(original.name); // "Ada"
shallow.tags.push("code");
console.log(original.tags); // ["math", "code"]
const assigned = Object.assign({}, original);
console.log(assigned.tags === original.tags); // trueChanging shallow.name does not affect the original, because name holds a primitive. The tags property holds a reference to an array, and only that reference was copied. Both objects share one array.
Deep Copies
A deep copy also copies every nested object, so nothing is shared with the original. structuredClone is the built-in way to make one. It is available in modern browsers and in Node.js 17 and later.
const original = { name: "Ada", tags: ["math"], joined: new Date(2020, 0, 1) };
const deep = structuredClone(original);
deep.tags.push("poetry");
console.log(original.tags); // ["math"]
console.log(deep.joined instanceof Date); // truestructuredClone keeps Date, Map, Set, and circular references intact. It still has limits, summarized below.
| Approach | Depth | Common problems |
|---|---|---|
| `{ ...obj }` / `Object.assign` | Shallow | Nested objects are shared |
| `JSON.parse(JSON.stringify(obj))` | Deep | Drops functions and `undefined`, turns `Date` into strings, throws on circular references |
| `structuredClone(obj)` | Deep | Throws on functions, loses class prototypes, turns getters into plain values |
Common Errors
- Mutating a "copy" made with
=. Assignment never copies an object. Use spread orstructuredClone. - Assuming spread is deep. Updating nested state such as
state.user.nameafter a spread changes the original. Spread each level you change:{ ...state, user: { ...state.user, name: "Lin" } }. - Comparing objects with
===to check contents. This only tells you whether two references point to the same object. Compare the properties you care about instead.
Exercise
After running const p = { pos: { x: 0 } }; const q = { ...p }; q.pos.x = 5; q.pos = { x: 9 };, what is p.pos.x, and why?
Show answer
It is 5. The spread copied the reference to the same pos object, so q.pos.x = 5 changed the shared object. The next line replaced q.pos with a new object, which affects only q. p.pos still points to the original, now-modified object.
Exercise
Why does structuredClone({ id: 1, greet() { return "hi"; } }) fail, and what is one way to copy this object?
Show answer
greet is a function, and structuredClone cannot clone functions, so it throws a DataCloneError. A shallow copy with { ...obj } works here, because the only other property is a primitive and the function reference can be shared.