Careeroza
Pure Functions & Immutability
Pure Functions
A pure function (1) always returns the same output for the same input and (2) has no side effects: it does not change outside variables, the DOM or its arguments. Pure functions are easy to test, cache and reason about.
Example
// impure: depends on and changes outside state
let total = 0;
function addToTotal(x) { total += x; return total; }
// pure
const add = (a, b) => a + b;
console.log(add(2, 3), add(2, 3));
console.log(addToTotal(5), addToTotal(5)); // different resultsOutput
5 5 5 10
Immutability
Example
Instead of changing data, create new data. Mutation bugs (one part of the app changing an object another part relies on) disappear:
const cart = Object.freeze({ items: [{ id: 1, qty: 1 }], coupon: null });
const addItem = (cart, item) => ({ ...cart, items: [...cart.items, item] });
const updateQty = (cart, id, qty) => ({
...cart,
items: cart.items.map((i) => (i.id === id ? { ...i, qty } : i)),
});
const next = updateQty(addItem(cart, { id: 2, qty: 3 }), 1, 5);
console.log(cart.items.length, next.items);Output
1 [ { id: 1, qty: 5 }, { id: 2, qty: 3 } ]