Sub topic 9
Shallow copies: what stays shared
This chapter assumes you know how toSorted, toSpliced, and with return new arrays. It also assumes you understand that JavaScript stores objects by reference: a variable holding an object holds a pointer to it, not the object itself.
The copying methods protect the array. They do not protect the things inside it. Each method builds a new array, but it fills that array with the same values the original held. For primitives such as numbers and strings, that makes no practical difference. For objects, both arrays end up pointing at the same objects.
What a shallow copy means
A shallow copy duplicates the outer container and nothing below it. The new array has its own slots, its own length, and its own order. Each slot that holds an object holds a reference to the same object the original slot pointed to.
Reordering, inserting, or replacing slots in byName never touches users. Changing a property on one of the shared objects shows up in both arrays, because only one object exists.
Seeing the sharing in code
const users = [{ name: "Linus" }, { name: "Ada" }];
const byName = users.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(byName === users); // false: different arrays
console.log(byName[0] === users[1]); // true: same object
byName[0].name = "Grace";
console.log(users[1].name); // "Grace"The sort did exactly what it promised. The bug came from the line after it, which mutated an object that both arrays share.
The common error
The usual mistake is to treat a copying method as a guarantee that nothing upstream can change. Code like this looks safe and is not:
const items = [{ id: 1, qty: 1 }, { id: 2, qty: 3 }];
const updated = items.with(0, items[0]);
updated[0].qty = 5;
console.log(items[0].qty); // 5: the original changed tooPassing items[0] to with puts the same object back into the new array. Calling with gave you a new array, but it did not give you a new element.
Copying the element you change
To change one element without affecting the original, create a new object for that element only:
const items = [{ id: 1, qty: 1 }, { id: 2, qty: 3 }];
const updated = items.with(0, { ...items[0], qty: 5 });
console.log(items[0].qty); // 1: original untouched
console.log(updated[0].qty); // 5
console.log(updated[1] === items[1]); // true: unchanged element still sharedSharing the untouched elements is usually what you want. It is cheap, and code that compares references can tell which elements changed and which did not.
When you need a full copy
If you need two arrays with no shared objects at all, make a deep copy first:
const users = [{ name: "Linus", roles: ["admin"] }, { name: "Ada", roles: [] }];
const independent = structuredClone(users).toSorted((a, b) =>
a.name.localeCompare(b.name)
);
independent[0].roles.push("editor");
console.log(users[1].roles); // []structuredClone copies nested data but throws on functions and DOM nodes, and it costs more than a shallow copy for large data. Use it only when you need the arrays to be fully independent.
| Approach | New array | New elements | Nested data copied |
|---|---|---|---|
| `toSorted`, `toSpliced`, `with` | Yes | No | No |
| `with(i, { ...arr[i] })` | Yes | Only at index `i` | No |
| `structuredClone(arr)` | Yes | Yes | Yes |
Exercise
Given const rows = [{ id: 1, tags: ["a"] }]; and const next = rows.with(0, { ...rows[0] });, what does rows[0].tags contain after running next[0].tags.push("b");?
Show answer
["a", "b"]. The spread creates a new row object, but its tags property still references the same array as the original row, so the push changes both. Use { ...rows[0], tags: [...rows[0].tags, "b"] } to avoid the shared change.
Exercise
After const sorted = list.toSorted(cmp);, which of these affects list: sorted.pop(), sorted[0] = {}, or sorted[0].count++ (assuming the elements are objects)?
Show answer
Only sorted[0].count++. The first two change the slots of the new array. The third mutates an object that both arrays reference.