Sub topic 11
Spread Copies Are Shallow
This chapter assumes you know how array spread ([...arr]) and object spread ({ ...obj }) build new values, as covered in earlier chapters. It also assumes you know that JavaScript stores objects, arrays, and functions as references, while numbers, strings, and booleans are copied as values.
Spread makes a new outer container. It does not make new copies of the objects stored inside that container. This difference causes many bugs that look like random corruption: you change a "copy" and the original changes as well. Here you will learn what spread actually copies, how to tell whether two values share data, and what to do when you need a fully independent copy.
What "shallow" means
A shallow copy creates a new top-level array or object and fills it with the same values the original holds. For a primitive value such as 'light' or 2, the value itself goes into the copy. For an object or array, the copy receives the reference, which points to the same object in memory. A deep copy, by contrast, repeats the copying at every level, so no nested object is shared.
const defaults = { theme: 'light', layout: { cols: 2 } };
const settings = { ...defaults, theme: 'dark' };
console.log(settings.theme); // 'dark' (later properties win)
console.log(defaults.theme); // 'light' (top level is independent)
settings.layout.cols = 3;
console.log(defaults.layout.cols); // 3 (nested object is shared)
console.log(settings.layout === defaults.layout); // trueSetting settings.theme changed a property on the new object only. Setting settings.layout.cols did not touch settings at all. It followed the layout reference to the one object that both settings and defaults point to, and it changed that object.
Shallow copies of arrays
Array spread behaves the same way. The new array has its own slots, so adding, removing, or reordering items affects only the copy. The items themselves are still shared when they are objects.
const todos = [
{ text: 'write', done: false },
{ text: 'test', done: false }
];
const copy = [...todos];
copy.push({ text: 'ship', done: false });
console.log(todos.length); // 2 (the array itself is separate)
copy[0].done = true;
console.log(todos[0].done); // true (the item object is shared)
console.log(copy[0] === todos[0]); // trueA common case is a two-dimensional grid. Spreading the outer array copies the rows by reference, so writing to a cell writes to the original grid.
const grid = [
[0, 0],
[0, 0]
];
const shallow = [...grid];
shallow[0][0] = 1;
console.log(grid[0][0]); // 1 (row arrays are shared)
const rowsCopied = grid.map(row => [...row]);
rowsCopied[1][1] = 9;
console.log(grid[1][1]); // 0 (each row was copied too)The map version copies two levels. That is enough for a grid of numbers. If the cells held objects, they would still be shared.
Mutation vs replacement
Sharing only causes trouble when you mutate a shared object, which means changing it in place. If you replace the nested value on the copy with a new one, the link to the original is broken for that property.
const original = { tags: ['a'] };
const copy = { ...original };
copy.tags = [...copy.tags, 'b']; // replacement: copy.tags is a new array
console.log(original.tags); // ['a']
copy.tags.push('c'); // mutates copy's own new array
console.log(original.tags); // ['a']
console.log(copy.tags); // ['a', 'b', 'c']This is the idea behind immutable updates. You spread at each level along the path you change and replace values instead of mutating them. A later chapter builds this into a full pattern. For now, keep one rule in mind: after a shallow copy, assignment to a top-level property is safe, but calling methods like push, sort, or splice, or assigning to a nested property, reaches the shared data.
Checking whether data is shared
Strict equality (===) on objects compares references. It returns true only when both sides are the same object, which makes it a direct test for sharing.
const a = { inner: { n: 1 } };
const b = { ...a };
console.log(a === b); // false (new outer object)
console.log(a.inner === b.inner); // true (same inner object)React and other libraries that check for changes rely on this behavior. They compare references to decide what changed. A shallow copy where you replaced only the changed branch keeps unchanged branches === to the old ones, so the library can skip them. Sharing unchanged data is therefore often useful. The bugs come from mutating shared data, not from sharing it.
Other shallow tools
Spread is not the only shallow copy in the language. All of these copy one level only:
| Technique | Produces | Depth |
|---|---|---|
| `[...arr]` | New array | Shallow |
| `arr.slice()` | New array | Shallow |
| `Array.from(arr)` | New array | Shallow |
| `{ ...obj }` | New plain object | Shallow |
| `Object.assign({}, obj)` | New plain object | Shallow |
| `structuredClone(value)` | New value at every level | Deep |
| `JSON.parse(JSON.stringify(value))` | New value at every level | Deep, but lossy |
Object spread also has two limits beyond depth. It copies only own enumerable properties, so inherited properties and methods on the prototype are left out. It also produces a plain object, so spreading an instance of a class gives you an object without that class's methods.
class Point {
constructor(x, y) { this.x = x; this.y = y; }
length() { return Math.hypot(this.x, this.y); }
}
const p = new Point(3, 4);
const q = { ...p };
console.log(q); // { x: 3, y: 4 }
console.log(q instanceof Point); // false
console.log(typeof q.length); // 'undefined'When you need a deep copy
Use structuredClone, a global function available in modern browsers and in Node.js 17 and later. It copies nested objects, arrays, Date, Map, Set, typed arrays, and even circular references.
const event = {
title: 'Launch',
when: new Date('2026-01-01T00:00:00Z'),
meta: { seats: 50 }
};
const deep = structuredClone(event);
deep.meta.seats = 10;
console.log(event.meta.seats); // 50 (fully independent)
console.log(deep.when instanceof Date); // true
const viaJson = JSON.parse(JSON.stringify(event));
console.log(typeof viaJson.when); // 'string' (Date was lost)
try {
structuredClone({ run() {} });
} catch (err) {
console.log(err.name); // 'DataCloneError'
}structuredClone has limits as well. It throws on functions, it drops class prototypes (a cloned Point becomes a plain object), and it does not copy getters or setters. The JSON round trip is worse. It turns dates into strings, drops undefined values and functions, turns NaN and Infinity into null, and throws on circular references.
Deep copies also cost more. They walk the whole structure and allocate memory for every nested value, and they throw away the reference sharing that change detection relies on. Use them when you need a fully independent snapshot, for example before handing data to code you do not control. For routine updates, prefer spreading along the path you change.
Common errors
- Assuming
const copy = { ...obj }protectsobjfrom every change made throughcopy. It protects only the top-level properties. - Copying an array of objects with spread and then editing items in place, such as
copy[i].done = true. Replace the item instead:copy[i] = { ...copy[i], done: true }. - Spreading a class instance and expecting its methods to be there afterward.
- Using the JSON round trip as a general deep copy and losing dates,
undefinedvalues, orMapcontents without any error.
Exercise
Given const a = { list: [1, 2], n: 1 }; const b = { ...a }; b.n = 2; b.list.push(3); b.list = [9];, what are a.n, a.list, and b.list at the end?
Show answer
a.n is 1, because assigning b.n changes only b's own property. a.list is [1, 2, 3], because push ran on the array that both objects shared at that moment. b.list is [9], because the last line replaced b's reference with a new array, which leaves a's array unchanged.
Exercise
You have const users = [{ name: 'Ada', active: false }] and want a new array where the first user is active, without changing users. Why does const next = [...users]; next[0].active = true; fail, and what is a correct version?
Show answer
The spread copies the array but not the user object, so next[0] and users[0] are the same object and the assignment changes the original. A correct version is const next = users.map((u, i) => i === 0 ? { ...u, active: true } : u);. It creates a new object for the changed user and keeps the unchanged users shared.