Lesson 1 of 9 · 22m
Immutability Without the Copy-Paste Cargo Cult
Why mutation makes JavaScript hard to reason about, how structural sharing changes the cost model, and when copying is the wrong instinct.
The first time immutability matters is never in a tutorial. It is the production bug where a table sorted itself, a cache entry changed after validation, or two components disagreed because they shared the same object. Mutation is not evil; uncontrolled aliasing is. Functional JavaScript is mostly the discipline of deciding who may change data and when.
The bug is shared mutable ownership
const user = { name: "Ada", roles: ["staff"] };
const draft = user;
draft.roles.push("admin");
console.log(user.roles); // ["staff", "admin"] — surpriseuser and draft are two names for one object. Once that object crosses module boundaries, every reader is secretly coupled to every writer. The failure rarely appears at the mutation site; it appears weeks later in a distant caller that trusted stale assumptions.
Copy at the boundary, not everywhere
const nextUser = {
...user,
roles: [...user.roles, "moderator"],
};Spread copies one level only. Nested data needs deliberate handling:
const next = {
...order,
customer: {
...order.customer,
address: { ...order.customer.address, postcode: "10001" },
},
};When this gets ugly, listen to it. Deeply nested updates mean the shape is wrong, the update belongs behind a domain function, or the app has outgrown hand-written copying.
Mutate locally when ownership is clear
function buildIndex(rows) {
const byId = {};
for (const row of rows) byId[row.id] = row;
return Object.freeze(byId);
}Mutation is fine while the value has not escaped. Once it is returned, cached, passed upward, or shared, treat it as read-only. Persistent structures and spread copies are usually cheap compared with rendering and network work; debugging accidental mutation is not.
Field notes
Object.freezeis shallow; freezingorderdoes not freezeorder.customer.push,splice,sort, andreversemutate.slice,map,concat, andtoSorteddo not.sort()is the classic trap because it mutates arrays that often alias props, caches, or API responses.- Know whether you need data-only cloning (
structuredClone) or domain-preserving construction. They solve different problems.
Was this lesson helpful?