
"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"]"
" 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"]"
Pure functions always return the same output for a given input and have no side effects, making them deterministic and predictable. Impure functions can mutate inputs and cause unexpected changes to shared references, as shown by a function that pushes an item into the original array. An immutable approach creates and returns a new array instead of modifying the original, preserving the original reference. Recreating data rather than updating it prevents race conditions and data battles, maintains stable references, and reduces surprising state changes in shared data contexts.
Read at InfoWorld
Unable to calculate read time
Collection
[
|
...
]