Pure functions are good
The key to immutability is understanding the notion of a pure function. A pure function is one that always returns the same output for a given input. Pure functions are said to be deterministic, in that the output is 100% predictable based on the input. In simpler terms, a pure function is a function with no side effects. It will never change something behind your back.
We’ve all had this experience:
function addPie(items: string[]) {
items.push("Apple Pie"); // side effect!
return items;
}
const order = ["Burger", "Fries"];
const before = order;
const updated = addPie(order);
console.log("before:", before); // ["Burger", "Fries", "Apple Pie"] ← oops
console.log("updated:", updated); // ["Burger", "Fries", "Apple Pie"]
Note the addPie
function, which is impure and thus has a side effect. It changes the items
array you send it. As a result, the before
reference changes as well. Not good—you might not expect that. When data is shared, being mutable turns everything into a moving target that is hard to hit.
But if the function provides immutability:
function addPieImmutable(items: string[]) {
return [...items, "Apple Pie"]; // no side effects, new array
}
const order = ["Burger", "Fries"];
const before = order;
const updated = addPieImmutable(order);
console.log("before:", before); // ["Burger", "Fries"] stable
console.log("updated:", updated); // ["Burger", "Fries", "Apple Pie"]
Here, the before
reference remains unchanged. Because instead of updating the order, we created a new one (updated
).
Change happens
Now this is a trivial example, but you can see how in the second version, there can never be a race condition or a battle for data because the order itself never changes. Instead, the order is recreated. Immutability doesn’t mean nothing changes; it means values never change once created. You still “change” by rebinding a name to a new value.
The notion of a “before” and “after” state is critical if you want features like undo, audit tracing, and other things that require a complete history of state.