What are Pure Functions?

A pure function always returns the same output for the same inputs and has no side effects: it does not modify its arguments, external variables, the DOM, storage or the network, and does not depend on anything that can change between calls.

The two rules

  1. Deterministic: same arguments, same result. No dependence on Date.now(), Math.random(), global mutable state, or the current time and user.
  2. No side effects: no mutating inputs, no writing to outer variables, no logging, no requests.

Why they are valuable

  • Easy to test: give inputs, assert outputs, no mocks or setup.
  • Easy to reason about: the signature tells the whole story.
  • Safe to memoise and cache, since results never change for the same input.
  • Safe to run in parallel, retry or reorder.
  • Framework requirements: React expects component rendering and state reducers to be pure (Strict Mode deliberately calls them twice to expose impurity), and Redux reducers must be pure.

Turning impure into pure

  • Pass the changing value in as an argument: formatDate(date, now) instead of reading new Date() inside.
  • Return a new value instead of mutating: [...list, item] instead of list.push(item).
  • Keep side effects at the edges of the program (event handlers, effects, API layers) and keep the core logic pure ("functional core, imperative shell").

Reality check

Programs need side effects to be useful. The goal is not zero side effects, but isolating them so most logic is pure.

Code example

js
1// Pure: depends only on inputs, returns a new value
2const addItem = (cart, item) => [...cart, item];
3const total = (cart) => cart.reduce((sum, i) => sum + i.price * i.qty, 0);
4
5// Impure: mutates its input and reads external state
6let discount = 0.1;
7function addItemImpure(cart, item) {
8 cart.push(item); // side effect: mutates the argument
9 return cart.length * (1 - discount); // depends on external variable
10}
11
12const cart = [{ name: "Book", price: 10, qty: 2 }];
13const next = addItem(cart, { name: "Pen", price: 2, qty: 3 });
14console.log(cart.length, next.length, total(next)); // 1 2 26
15
16// Make time-dependent logic pure by passing time in
17const isExpired = (expiresAt, now) => now >= expiresAt;
18console.log(isExpired(1000, 999), isExpired(1000, 1000)); // false true
19// in the app: isExpired(token.expiresAt, Date.now()) <- the impure part stays at the edge
20
21// Pure functions are trivially testable and memoisable
22const assertEqual = (a, b) => console.log(JSON.stringify(a) === JSON.stringify(b) ? "pass" : "FAIL");
23assertEqual(total([{ price: 5, qty: 2 }]), 10); // pass
24assertEqual(addItem([], 1), [1]); // pass

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app