Pure features are good
The important thing to immutability is knowing the notion of a pure operate. A pure operate is one which at all times returns the identical output for a given enter. Pure features are mentioned to be deterministic, in that the output is 100% predictable based mostly on the enter. In easier phrases, a pure operate is a operate with no unwanted side effects. It should by no means change one thing behind your again.
We’ve all had this expertise:
operate addPie(objects: string[]) { objects.push("Apple Pie"); // aspect impact! return objects; } const order = ["Burger", "Fries"]; const earlier than = order; const up to date = addPie(order); console.log("earlier than:", earlier than); // ["Burger", "Fries", "Apple Pie"] ← oops console.log("up to date:", up to date); // ["Burger", "Fries", "Apple Pie"]
Notice the addPie
operate, which is impure and thus has a aspect impact. It modifications the objects
array you ship it. Consequently, the earlier than
reference modifications as nicely. Not good—you may not anticipate that. When knowledge is shared, being mutable turns every part right into a shifting goal that’s arduous to hit.
But when the operate supplies immutability:
operate addPieImmutable(objects: string[]) { return [...items, "Apple Pie"]; // no unwanted side effects, new array } const order = ["Burger", "Fries"]; const earlier than = order; const up to date = addPieImmutable(order); console.log("earlier than:", earlier than); // ["Burger", "Fries"] secure console.log("up to date:", up to date); // ["Burger", "Fries", "Apple Pie"]
Right here, the earlier than
reference stays unchanged. As a result of as a substitute of updating the order, we created a brand new one (up to date
).
Change occurs
Now this can be a trivial instance, however you may see how within the second model, there can by no means be a race situation or a battle for knowledge as a result of the order itself by no means modifications. As a substitute, the order is recreated. Immutability doesn’t imply nothing modifications; it means values by no means change as soon as created. You continue to “change” by rebinding a reputation to a brand new worth.
The notion of a “earlier than” and “after” state is crucial if you’d like options like undo, audit tracing, and different issues that require a whole historical past of state.