Sub topic 9
Shallow copies: what stays shared
This chapter assumes you already know how toSorted, toSpliced, and with return new arrays. It also assumes you understand the difference between primitive values and object references. The chapter covers a question those methods leave open: when the array holds objects, how much of it is actually new?
The answer is one level. Each copying method builds a new array object and fills its slots with the same values the original held. A number or string in a slot is just a value. An object in a slot is a reference, and the copy gets the same reference. Both arrays then point at one shared object.
What "shallow" means in practice
A shallow copy duplicates the container and nothing inside it. The new array has its own length and its own slots. You can reorder, insert, or replace slots in it without touching the original. The things those slots refer to are not duplicated.
const users = [{ name: "Linus" }, { name: "Ada" }];
const byName = users.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(byName[0] === users[1]); // true
byName[0].name = "Grace";
console.log(users[1].name); // "Grace"byName and users are different arrays, so byName !== users. The objects inside them are not different. byName[0] and users[1] are the same object, and the === check confirms it. Changing .name through one array changes what the other array sees, because only one object exists.
What is copied and what is shared
| Part of the structure | After `toSorted`, `toSpliced`, or `with` |
|---|---|
| The array object itself | New. `copy !== original` |
| Slot order and length | Independent. Changing one does not affect the other |
| Primitive elements (numbers, strings, booleans) | Copied by value. Nothing to share |
| Object, array, or function elements | Shared. Same reference in both arrays |
| Properties of those objects | Shared, because the objects are shared |
| Frozen state of the original array | Not carried over. The copy is a normal, extensible array |
Primitives are safe because nothing can mutate them. copy[0] = 99 replaces a slot. It does not change the number that original[0] holds. The risk only shows up with objects, and only when someone mutates a property instead of replacing the slot.
The same rule applies to nested arrays
An array inside an array is an object, so it is shared like any other object.
const grid = [[1, 2], [3, 4]];
const flipped = grid.toReversed();
console.log(flipped); // [[3, 4], [1, 2]]
flipped[0].push(5);
console.log(grid[1]); // [3, 4, 5]
console.log(flipped[0] === grid[1]); // truetoReversed reordered the outer slots. The inner rows are the same row arrays in both grids, so push on one is visible through the other. People hit this bug when they assume "immutable method" means "nothing in my data can change." The method itself mutates nothing. Your later code can still mutate the shared parts.
Replacing a slot versus mutating an element
with replaces whatever sits in one slot. It never reaches into the element that was there.
const items = [{ id: 1, qty: 1 }, { id: 2, qty: 1 }];
// Safe: a new object goes into slot 0 of a new array
const safe = items.with(0, { ...items[0], qty: 5 });
console.log(items[0].qty); // 1
console.log(safe[1] === items[1]); // true
// Unsafe: the copy is new, but the element is mutated in place
const unsafe = items.with(1, items[1]);
unsafe[1].qty = 9;
console.log(items[1].qty); // 9The first update creates a new array and a new object for the one element that changes. The untouched element stays shared, and that is intentional. The second update makes a new array but then mutates a shared object, which defeats the purpose.
Updating one level deeper: structural sharing
To change a value inside a nested structure without touching the original, copy each level along the path to the change and share everything else. This is called structural sharing.
const grid = [[1, 2], [3, 4]];
const updated = grid.with(1, grid[1].with(0, 30));
console.log(updated); // [[1, 2], [30, 4]]
console.log(grid); // [[1, 2], [3, 4]]
console.log(updated[0] === grid[0]); // true (unchanged row is shared)
console.log(updated[1] === grid[1]); // false (changed row is new)Only the outer array and row 1 are new. Row 0 is reused. This costs much less than copying everything, and it gives a clear signal: any reference that changed marks a part of the structure that changed. The chapter on React and Redux state builds on this property.
The same pattern works for arrays of objects:
const teams = [
{ name: "Core", members: ["Ada", "Linus"] },
{ name: "Docs", members: ["Grace"] }
];
const next = teams.with(1, {
...teams[1],
members: teams[1].members.toSpliced(1, 0, "Margaret")
});
console.log(next[1].members); // ["Grace", "Margaret"]
console.log(teams[1].members); // ["Grace"]
console.log(next[0] === teams[0]); // trueThree things are new here: the outer array, the Docs object, and its members array. The Core object is shared.
When you really need a deep copy
Sometimes you need a fully independent copy, for example before giving data to code you don't control that may mutate it. structuredClone copies every level.
const users = [{ name: "Linus", tags: ["kernel"] }];
const deep = structuredClone(users);
deep[0].tags.push("git");
console.log(users[0].tags); // ["kernel"]
console.log(deep[0] === users[0]); // falseKnow its limits before you reach for it:
- It throws a
DataCloneErroron functions and DOM nodes. - Class instances come back as plain objects and lose their prototype methods.
- It copies everything, so on large data it takes much more time and memory than structural sharing.
A common middle option is to copy exactly one extra level with map:
const rows = [[1, 2], [3, 4]];
const independentRows = rows.map(row => [...row]);
independentRows[0].push(99);
console.log(rows[0]); // [1, 2]Freezing is shallow too
Object.freeze stops changes to the array's own slots but not to the objects in them. The copying methods also return an ordinary array, not a frozen one.
"use strict";
const frozen = Object.freeze([{ n: 1 }, { n: 2 }]);
const copy = frozen.toReversed();
console.log(Object.isFrozen(copy)); // false
copy.push({ n: 3 }); // allowed
frozen[0].n = 10; // allowed: the element object is not frozen
console.log(copy[1].n); // 10Calling toReversed on a frozen array works because it never writes to the receiver. Calling frozen.reverse() would throw a TypeError in strict mode. That is one practical gain: copying methods are safe to call on frozen data. Freezing does not make the elements immutable.
Common errors
- Assuming the copy is deep. You mutate
copy[i].fieldand then find the original changed too. Fix it by replacing the element:copy.with(i, { ...copy[i], field }). - Spreading only the outer level of nested data.
{ ...obj }copies one level, just liketoSorted. Nested arrays insideobjare still shared. - Copying everything "to be safe." Calling
structuredClonebefore each update discards structural sharing. Reference checks (prev[i] === next[i]) then report every element as changed. - Treating
===on the arrays as proof of a change.next !== prevtells you the container is new. It says nothing about whether any element is new.
Exercise
Given const a = [{ v: 1 }, { v: 2 }]; const b = a.toSorted((x, y) => y.v - x.v); b[0].v = 50; what are a[0].v, a[1].v, and b[0] === a[1]?
Show answer
a[0].v is 1, a[1].v is 50, and b[0] === a[1] is true. Sorting in descending order puts the { v: 2 } object first in b. That object is the same one as a[1], so setting .v to 50 through b[0] changes a[1].
Exercise
Starting from const board = [["x", ""], ["", "o"]];, write one expression that returns a new board with board[0][1] set to "o". It must leave board unchanged and reuse board[1].
Show answer
board.with(0, board[0].with(1, "o")). It creates a new outer array and a new row 0. The result's [1] is the same array as board[1], so result[1] === board[1] is true.
Exercise
Why does Object.freeze(list).toSorted() succeed when Object.freeze(list).sort() throws in strict mode, and does the frozen array protect the objects inside it?
Show answer
toSorted only reads the receiver and writes to a new array, so freezing the receiver does not affect it. sort writes to the frozen array's own slots and throws a TypeError. Freezing is shallow, so the element objects can still be mutated unless you freeze each of them too.