Sub topic 10
Objects as References: Shallow and Deep Copies
This chapter assumes you can create object literals, read and write properties, and use spread syntax on arrays. It also assumes you know how to list properties with Object.keys and Object.entries, which the previous chapter covered. Here you will see why assigning an object never copies it, how shallow copies share nested data, and which deep-copy tool to choose for which kind of data.
Variables Hold References, Not Objects
A primitive value such as a number or string is stored directly in the variable. An object is different. The variable holds a reference, which is a pointer to an object that lives somewhere in memory. When you assign one variable to another, JavaScript copies the reference. The object itself is not copied.
const a = { score: 1 };
const b = a;
b.score = 99;
console.log(a.score); // 99
console.log(a === b); // true
console.log({ score: 1 } === { score: 1 }); // falsea and b point to the same object, so a change made through one name shows up through the other. The last line shows the other half of the rule: === on objects compares identity. Two separately created objects are never equal, even when their contents match.
const does not change any of this. It stops you from pointing the variable at a different object. It does not stop anyone from changing the object the variable points to.
Passing Objects to Functions
Function arguments follow the same rule. The function receives a copy of the reference, so it can mutate the caller's object. Reassigning the parameter has no effect outside the function.
function reset(obj) {
obj.score = 0; // mutates the shared object
}
function replace(obj) {
obj = { score: -1 }; // rebinds the local parameter only
}
const player = { score: 42 };
reset(player);
console.log(player.score); // 0
replace(player);
console.log(player.score); // 0People sometimes call this "pass by reference," but that name is not accurate. JavaScript passes the reference by value. If it were true pass by reference, replace would have changed player.
Shallow Copies
A shallow copy is a new object whose top-level properties are copied from the original. If a property holds a primitive, the copy gets its own value. If a property holds an object, the copy gets the same reference, so the nested object is shared.
const original = { name: "Ada", tags: ["math"] };
const shallow = { ...original };
shallow.name = "Grace";
shallow.tags.push("code");
console.log(original.name); // "Ada"
console.log(original.tags); // ["math", "code"]
console.log(shallow.tags === original.tags); // trueRenaming shallow.name leaves the original alone because name holds a string. Pushing to shallow.tags changes the array that both objects point to.
Spread Versus Object.assign
{ ...obj } and Object.assign({}, obj) both make shallow copies, and both copy only own enumerable properties, including symbol-keyed ones. They write those properties in different ways:
- Spread defines new data properties on the new object.
Object.assignsets properties on the target. If the target has a setter with that name, the setter runs.
const target = {
set name(v) {
console.log("setter ran with", v);
}
};
Object.assign(target, { name: "Ada" }); // logs: setter ran with Ada
const spreadCopy = { ...target, name: "Ada" }; // logs nothing
console.log(Object.getOwnPropertyDescriptor(spreadCopy, "name"));
// { value: 'Ada', writable: true, enumerable: true, configurable: true }The difference matters when you merge into an existing object that has accessors, which a later chapter covers. To copy into a fresh object, spread is the usual choice. Use Object.assign when you mean to update an existing object in place.
What a Shallow Copy Loses
Both techniques read the source's values and produce a plain object. Three things are lost along the way:
- The prototype. A copy of a class instance is a plain object and has none of the class methods.
- Getters and setters. A getter is called once and its current result is stored as an ordinary value.
- Non-enumerable properties. These are skipped completely.
class Point {
constructor(x) {
this.x = x;
}
describe() {
return `x=${this.x}`;
}
}
const p = new Point(3);
const copy = { ...p };
console.log(copy.x); // 3
console.log(typeof copy.describe); // "undefined"
console.log(copy instanceof Point); // false
const sameKind = Object.assign(Object.create(Object.getPrototypeOf(p)), p);
console.log(sameKind.describe()); // "x=3"The last pattern makes a new object with the same prototype and then copies the own properties onto it. The chapter on the prototype chain explains why that brings the methods back.
Deep Copies
A deep copy recursively copies every nested object, so the result shares no mutable state with the original. Modern JavaScript has a built-in function for this, structuredClone, which is available in all current browsers and in Node.js 17 and later.
const state = {
created: new Date(2024, 0, 1),
tags: new Set(["a"]),
nested: { level: 1 }
};
state.self = state; // a circular reference
const clone = structuredClone(state);
console.log(clone.created instanceof Date); // true
console.log(clone.tags.has("a")); // true
console.log(clone.nested === state.nested); // false
console.log(clone.self === clone); // true
clone.nested.level = 2;
console.log(state.nested.level); // 1structuredClone uses the structured clone algorithm, the same one browsers use to send data between workers. It keeps Date, Map, Set, RegExp, ArrayBuffer, typed arrays, and most Error types. It also tracks the objects it has already copied, so circular references come out as circular references in the clone and do not cause infinite recursion.
structuredClone's Limits
The algorithm copies data, not behavior. Expect these results:
| Input | Result |
|---|---|
| Function, or a property holding one | Throws `DataCloneError` |
| Class instance | Plain object, prototype lost |
| Getter | Called once, stored as a data property |
| Symbol-keyed property | Silently dropped |
| Non-enumerable property | Silently dropped |
| DOM node (browser) | Throws `DataCloneError` |
try {
structuredClone({ greet() {} });
} catch (e) {
console.log(e.name); // "DataCloneError"
}Method shorthand creates a function-valued property, so any object with methods fails to clone. If you need to deep-copy objects that carry behavior, write a dedicated copy method or use a library that knows your types.
The JSON Round-Trip and Its Traps
Older code often deep-copies with JSON.parse(JSON.stringify(obj)). It works only for data that JSON can represent exactly, and it fails quietly on anything else:
const data = {
when: new Date(0),
missing: undefined,
ratio: NaN,
greet() {}
};
const viaJson = JSON.parse(JSON.stringify(data));
console.log(viaJson);
// { when: '1970-01-01T00:00:00.000Z', ratio: null }The Date became a string, undefined and the method disappeared, and NaN turned into null. Map and Set become {}, Infinity becomes null, and BigInt or circular references throw a TypeError. Use the JSON round-trip only when you are serializing data anyway, for example to send it over the network. For in-memory copies, prefer structuredClone.
Choosing a Copy Strategy
| Need | Tool | Notes |
|---|---|---|
| Share the same object | `b = a` | No copy at all |
| New top-level object, flat data | `{ ...obj }` | Nested objects shared |
| Update an existing object in place | `Object.assign(target, src)` | Runs setters on the target |
| Independent copy of plain data, dates, maps, cycles | `structuredClone(obj)` | Throws on functions, drops prototypes |
| Data headed for JSON anyway | `JSON.parse(JSON.stringify(obj))` | Lossy on many types |
| Change one nested value without mutation | Nested spread | Copies only the changed path |
Updating Nested Data Without Mutation
Frameworks such as React rely on reference changes to detect updates. The usual pattern spreads each level along the path that changes and leaves every other branch shared:
const prev = {
user: { name: "Lin", address: { city: "Oslo" } },
settings: { theme: "dark" }
};
const next = {
...prev,
user: {
...prev.user,
address: { ...prev.user.address, city: "Bergen" }
}
};
console.log(prev.user.address.city); // "Oslo"
console.log(next.user.address.city); // "Bergen"
console.log(next.settings === prev.settings); // true: untouched branch shared
console.log(next.user === prev.user); // false: changed path copiedBecause the untouched branches keep their identity, a cheap === check tells you which parts changed.
Common Mistakes
- Treating
constas a guarantee that the object will not change. It only fixes the variable's binding. - Spreading an object and then mutating a nested array or object, which changes the original.
- Comparing objects with
===to test whether their contents are equal. Compare the specific fields instead, or use a deep-equality helper. - Calling
structuredCloneon objects that contain methods and getting aDataCloneErrorat runtime. - Using the JSON round-trip on data that contains dates,
undefined, orMaps and losing information without any error.
Exercise
Given const a = { list: [1] }; const b = { ...a }; b.list = [2]; b.list.push(3);, what are a.list and b.list, and why?
Show answer
a.list is [1] and b.list is [2, 3]. The spread copied the reference to [1], but b.list = [2] replaced b's property with a reference to a new array. The push then changes only that new array, so the original is untouched.
Exercise
You call structuredClone(order) where order is an instance of a class Order with a total() method and a createdAt Date property. What happens, and what does the clone look like?
Show answer
The call succeeds, because class methods live on the prototype and are not own properties, so the algorithm never meets a function. The clone is a plain object: clone instanceof Order is false and clone.total is undefined. clone.createdAt is a new, independent Date. The call would throw DataCloneError only if a function were stored as an own property, for example a method defined directly on the object.
Exercise
Write an expression that produces a new version of state = { cart: { items: ["pen"], coupon: null }, user: { id: 1 } } with "ink" appended to items, without mutating state and keeping state.user shared.
Show answer
const next = { ...state, cart: { ...state.cart, items: [...state.cart.items, "ink"] } }; Afterwards state.cart.items is still ["pen"], next.cart.items is ["pen", "ink"], and next.user === state.user is true.