Immutability
Иммутабельность
An immutable value keeps the same contents once it’s created. To represent a change, you use a new value rather than editing the original in place.
Also known as: неизменяемость
Why immutability matters
Say you save the current shopping cart so the user can undo their next action. If the saved cart and the current cart refer to the same mutable list, removing an item from that list changes both. Saving the reference didn’t save a snapshot. With immutable cart data, an update produces a new version, and the reference you saved still gives you the old contents.
A variable and the value it holds are separate things. Python strings are immutable, but name = name.upper() is valid: the assignment makes name refer to the result without rewriting the original string. The reverse is possible too. In JavaScript, const prevents reassignment, but an ordinary array declared with const can still be changed with push.
Update the path, not the original
Suppose an application tracks whether an order has shipped. To produce updated state without changing the previous state, copy the objects along the path to the changed field:
const before = { order: { shipped: false }, currency: 'USD' };
const after = {
...before,
order: { ...before.order, shipped: true },
};
console.log(before.order.shipped); // false
console.log(after.order.shipped); // true
Object spread is shallow. Spreading before alone would leave both state objects pointing to the same order. The code above avoids mutating the input, but it does not make the resulting objects immutable. Likewise, Object.freeze(before) would freeze the outer object, not its nested order object.
When the trade-off pays off
Immutable updates work well for undo history, snapshots, and functions that transform data without modifying their inputs. They also make reference equality useful: if a React component is memoized and a prop still points to the same object, treating that prop as unchanged is sound only if its contents haven’t been mutated. Creating new objects for everything on every update, however, can defeat that optimization.
Copying a large collection on every edit can cost time and memory. Persistent data structures reduce that cost by letting versions share unchanged parts. Immutability also makes fixed snapshots easier to share across threads, but it doesn’t coordinate writes to a shared variable that holds the latest snapshot. Two threads can build conflicting updates from the same old version, and one update can overwrite the other.
What interviewers look for
Expect a small code sample with two references to the same nested object. Trace which objects are shared, then explain which references your update must replace. Saying “make a copy” isn’t enough: the key is knowing what the copy still shares with the original.