Sub topic 4
Pure Functions and Referential Transparency
This chapter assumes you know core JavaScript syntax, arrow functions, spread syntax, and how scope works. It also builds on the previous chapters: functions are values, and closures can capture variables from an outer scope. Here you will learn what makes a function pure, why that property makes code easier to reason about, and the common mistakes that quietly make a function impure.
What a pure function is
A function is pure when it meets two conditions:
- Determinism. Given the same arguments, it always returns the same result. Its output depends only on its inputs.
- No observable side effects. Calling it changes nothing outside the function. It does not modify arguments, global variables, the DOM, files, or the network, and it does not write logs.
The contrast is easiest to see side by side:
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 breaks both rules. It reads total, which is a hidden input, and it writes total, which is a side effect. The result of a call depends on how many calls came before it. add has none of these problems. To understand it, you only need to read its parameter list and its body.
Referential transparency
An expression is referentially transparent if you can replace it with its value without changing what the program does. When a function is pure, every call to it is referentially transparent.
const square = (x) => x * x;
const a = square(4) + square(4);
const b = 16 + 16;
console.log(a === b); // true: square(4) can always be replaced by 16You cannot make that substitution with addToTotal(5). If you replaced the first call with 5, the second call would return 5 instead of 10, so the program would behave differently.
Substitution is what makes reasoning easy. When every piece of an expression is transparent, you can evaluate it in your head one step at a time, the way you simplify algebra. Several practical benefits follow:
- Testing. A pure function needs no mocks, setup, or teardown. You pass in arguments and check what comes back.
- Caching. If
f(x)always gives the same value, you can store it and reuse it. The memoization chapter depends on this. - Reordering and parallelism. Pure calls do not depend on each other through shared state, so they can run in any order.
- Refactoring. You can extract, inline, or move a pure call without checking what else it touches.
Hidden inputs: the first common error
A function can look pure and still read state that is not in its parameter list. These are the usual culprits:
let discount = 0.1;
const config = { rate: 0.2 };
const TAX = 0.2;
// Pure in practice: TAX is a const primitive and can never change
const withTax = (price) => price * (1 + TAX);
// Impure: discount is reassignable
const discounted = (price) => price * (1 - discount);
// Impure: config is const, but its properties can still be changed
const withRate = (price) => price * (1 + config.rate);
// Impure: the result depends on the clock
const isExpired = (expiry) => Date.now() > expiry;
// Pure: the time is now an explicit argument
const isExpiredAt = (expiry, now) => now > expiry;
console.log(withTax(100)); // 120
console.log(isExpiredAt(1000, 2000)); // true
config.rate = 0.5;
console.log(withRate(100)); // 150, changed with no change to the callconst freezes the binding, not the value. A const holding a primitive is safe to read. A const holding an object or array is not, because someone can change its contents. Closures follow the same rule. A closure that captures a variable that never changes is still pure. A closure that captures mutable state, like the counter from the closures chapter, is impure.
The general fix is to turn hidden inputs into parameters. isExpiredAt does the same job as isExpired but takes the clock reading as an argument. The caller, usually code at the edge of the program, decides where that value comes from.
| Hidden input | Why it breaks purity | Pure alternative |
|---|---|---|
| `Date.now()`, `new Date()` | Different on every call | Pass `now` as an argument |
| `Math.random()` | Different on every call | Pass the random value or a seeded generator |
| Reassignable outer `let` | Can change between calls | Pass the value as an argument |
| Properties of a shared object | Can be changed elsewhere | Pass the value, or freeze or copy the object |
| `this` in a method | Depends on how the function was called | Pass the object explicitly |
| `localStorage`, DOM, `process.env` | External, mutable environment | Read it once at the edge, then pass it in |
Mutating arguments: the second common error
Objects and arrays are passed by reference. If a function changes them, the change is visible to the caller, and that is a side effect even when the function returns the "right" value.
// Impure: changes the caller's array
const addItemImpure = (cart, item) => {
cart.push(item);
return cart;
};
// Pure: returns a new array, leaves the input alone
const addItem = (cart, item) => [...cart, item];
const cart = ['apple'];
const next = addItem(cart, 'pear');
console.log(cart, next); // [ 'apple' ] [ 'apple', 'pear' ]
addItemImpure(cart, 'plum');
console.log(cart); // [ 'apple', 'plum' ]: the caller's data changedSome built-in methods mutate in place, which makes this mistake easy to make. sort, reverse, splice, push, pop, shift, unshift, fill, and Object.assign(target, ...) all change their target.
const scores = [70, 95, 82];
// Impure: sort reorders the caller's array
const highestImpure = (xs) => xs.sort((a, b) => b - a)[0];
// Pure: sort a copy
const highest = (xs) => [...xs].sort((a, b) => b - a)[0];
console.log(highest(scores), scores); // 95 [ 70, 95, 82 ]
console.log(highestImpure(scores), scores); // 95 [ 95, 82, 70 ]The chapter on working without mutation covers copying techniques, including nested updates and toSorted, in detail.
Edge cases and grey areas
Local mutation is fine
Purity describes what callers can observe. A function can mutate variables it creates itself and still be pure:
const sumTo = (n) => {
let total = 0;
for (let i = 1; i <= n; i += 1) total += i;
return total;
};
console.log(sumTo(100)); // 5050, every timeNo caller can see total or i, so this function is pure. Do not rewrite fast, clear loops just to look more "functional".
Logging and debugging
Strictly speaking, console.log is a side effect. Most teams accept temporary debug logging inside pure code because it does not affect the program's result. Logging that is part of the required behavior, such as audit logs, is a real effect and belongs in the side-effect layer described in the next chapter.
Throwing exceptions
parse('bad') may throw the same error every time. That is deterministic, but a throw is not a value you can substitute for the call, and it skips the rest of the expression. Many codebases treat functions that throw on invalid input as "pure enough". Stricter styles return a value that represents failure instead. The Maybe chapter shows one way to do that.
New objects and identity
const point = (x, y) => ({ x, y });
console.log(point(1, 2) === point(1, 2)); // falseEach call returns a new object, so === reports them as different. The function is still pure: the results are structurally equal, and it changes nothing outside itself. This matters when a framework compares by reference. For example, React re-renders when it receives a new object, even if that object is structurally equal to the old one.
Cost
Pure updates allocate new arrays and objects. For typical UI or business data this cost is negligible. In hot loops over large data it can show up in profiles, and local mutation inside a function that is pure from the outside is a reasonable compromise.
Testing pure functions
Because a pure function's behavior is fully described by inputs and outputs, a test is just a table of cases:
const assert = require('node:assert/strict');
const isExpiredAt = (expiry, now) => now > expiry;
const addItem = (cart, item) => [...cart, item];
assert.equal(isExpiredAt(1000, 2000), true);
assert.equal(isExpiredAt(1000, 500), false);
const original = ['a'];
assert.deepEqual(addItem(original, 'b'), ['a', 'b']);
assert.deepEqual(original, ['a']); // input untouched
console.log('all tests passed');To test the impure isExpired, you would need to fake the system clock. Making the time a parameter removed that work.
Summary
- A pure function is deterministic and has no observable side effects.
- Calls to pure functions are referentially transparent: you can replace any call with its result.
- The two most common ways to break purity are reading hidden inputs and mutating arguments.
- You fix hidden inputs by passing them in as parameters, and you avoid mutation by returning new values.
- Local mutation, new object identity, and deterministic throws are grey areas. Judge each one by what a caller can observe.
Exercise
Classify each function as pure or impure and give the reason. (a) const greet = (name) => Hi, ${name}; (b) const stamp = (msg) => ${new Date().toISOString()} ${msg}; (c) const last = (xs) => xs.pop(); (d) const ids = []; const register = (id) => ids.concat(id);
Show answer
(a) Pure: the output depends only on name, and nothing outside changes. (b) Impure: it reads the clock, which is a hidden input. (c) Impure: pop removes an element from the caller's array, which is a side effect. (d) Pure in behavior: concat returns a new array and does not change ids. Because ids is a const array, it could be mutated elsewhere, which would change the result. Passing the list as a parameter makes the function fully pure.
Exercise
Rewrite this function so it is pure and testable without faking anything: const greeting = () => (new Date().getHours() < 12 ? 'Good morning' : 'Good afternoon');
Show answer
Make the hour an argument: const greetingAt = (hour) => (hour < 12 ? 'Good morning' : 'Good afternoon'); Call greetingAt(new Date().getHours()) at the edge of the program. Tests can then check greetingAt(9) === 'Good morning' and greetingAt(15) === 'Good afternoon' directly.
Exercise
A teammate says sumTo below is impure because it reassigns total. Are they right? const sumTo = (n) => { let total = 0; for (let i = 1; i <= n; i++) total += i; return total; };
Show answer
No. total and i are local to each call, so no caller can observe them changing. The same n always produces the same result, and nothing outside the function is changed, so sumTo is pure.