How Immutibility to twist the Wild West

Pure functions are good

The key to invariance is to understand the concept of pure function. A pure function is one that Always Returns the same output for the input. Pure functions are said to be deterministic because the output is 100% predictable. Put simply, a pure function is a function without side effects. It never changes something behind your back.

We 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")

Notice addPie A function that is unclean and therefore has a side effect. It changes items The fields to send it. As a result before Also changes in references. It’s not good – maybe you don’t expect it. When the data is shared, it must be necessary to change everything to a moving goal that is difficult to intervene.

But if the function provides non -changeability:


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, before The reference remains unchanged. Becaus Intear about updating the order, we created a new one (updated).

Change becomes

Now this is a trivial example, but you can see how there is no condition of the race or battle for data in the second version, because the order itself will never change. Instead, the order is re -created. Immnutability does not mean that nothing will change; This means that the values ​​will never change as soon as they are created. You still “change” by waking up the name to a new value.

The idea of ​​the state of “before” and “after” is critical if you want functions such as back, watching an audit, and another thing that requires a complete history of the state.

Leave a Comment