Sub topic 4
Pure Functions and Referential Transparency
This chapter assumes you know JavaScript functions, arrow syntax, and spread syntax, and that you have read the earlier chapters on functions as values and closures.
A pure function follows two rules:
- Its return value depends only on its arguments.
- It has no side effects. It does not change variables outside itself, mutate its arguments, write to the console, or make network calls.
When a function breaks either rule, it is impure.
Comparing the two
let total = 0;
// Impure: reads and changes state outside the function
function addToTotal(n) {
total += n;
return total;
}
// Pure: output depends only on inputs, no side effects
function add(a, b) {
return a + b;
}
console.log(addToTotal(5)); // 5
console.log(addToTotal(5)); // 10 (same input, different result)
console.log(add(2, 3)); // 5, every timeaddToTotal returns a different result for the same input because it depends on total, and it changes total too. You can't predict what it returns without knowing every call that happened before it. To predict what add returns, you only need its arguments.
Referential transparency
An expression is referentially transparent if you can replace it with its value and the program behaves the same. Calls to pure functions have this property:
const add = (a, b) => a + b;
const x = add(2, 3) * add(2, 3);
const y = 5 * 5; // same meaning: add(2, 3) can be replaced by 5
console.log(x === y); // trueYou can't do this with addToTotal(5). Replacing it with 5 changes what the program does, because the call also updates total.
Referential transparency is what makes pure code easy to reason about. You can read a function on its own. You can test it with plain input and output assertions. You can cache its results (the memoization chapter shows how), and you can reorder or remove calls whose results go unused without breaking anything.
Common hidden impurities
Some impurities are easy to miss:
| Hidden dependency or effect | Example | Why it is impure |
|---|---|---|
| Current time | `Date.now()` | Returns a different value on each call |
| Randomness | `Math.random()` | Returns a different value on each call |
| Mutating an argument | `arr.push(x)`, `arr.sort()` | Changes data the caller still holds |
| Reading outer mutable state | `let rate` read inside the function | Result changes when `rate` changes |
| I/O | `console.log`, `fetch` | Has an effect outside the function |
Mutating an argument is the most common mistake:
// Impure: the caller's array is modified
function addItemImpure(cart, item) {
cart.push(item);
return cart;
}
// Pure: returns a new array
const addItem = (cart, item) => [...cart, item];
const cart = ['apple'];
const next = addItem(cart, 'pear');
console.log(cart); // [ 'apple' ]
console.log(next); // [ 'apple', 'pear' ]To make a function that depends on time or randomness pure, pass the value in as an argument:
const isExpired = (expiresAt, now) => now > expiresAt;
console.log(isExpired(1000, 2000)); // true, every time
console.log(isExpired(1000, Date.now())); // the impure part stays at the call siteA program made only of pure functions can't do anything useful, because showing output is itself a side effect. The aim is to keep most of your logic pure and push effects to the edges of the program. The next chapter covers how to do that.
Exercise
Is const greet = (name) => \Hello, ${name}\` pure? What about const greetLog = (name) => console.log(\Hello, ${name}\)`? Explain each.
Show answer
greet is pure. Its result depends only on name, and it changes nothing outside itself. greetLog is impure because writing to the console is a side effect. Its return value is always undefined, so you can't replace a call with its value without losing the output.
Exercise
Rewrite function applyDiscount(order) { order.total = order.total * 0.9; return order; } as a pure function.
Show answer
const applyDiscount = (order) => ({ ...order, total: order.total * 0.9 }); returns a new object and leaves the original order unchanged.