JavaScriptMedium
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
- Deterministic: same arguments, same result. No dependence on
Date.now(),Math.random(), global mutable state, or the current time and user. - 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 readingnew Date()inside. - Return a new value instead of mutating:
[...list, item]instead oflist.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 value2const addItem = (cart, item) => [...cart, item];3const total = (cart) => cart.reduce((sum, i) => sum + i.price * i.qty, 0);45// Impure: mutates its input and reads external state6let discount = 0.1;7function addItemImpure(cart, item) {8 cart.push(item); // side effect: mutates the argument9 return cart.length * (1 - discount); // depends on external variable10}1112const 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 261516// Make time-dependent logic pure by passing time in17const isExpired = (expiresAt, now) => now >= expiresAt;18console.log(isExpired(1000, 999), isExpired(1000, 1000)); // false true19// in the app: isExpired(token.expiresAt, Date.now()) <- the impure part stays at the edge2021// Pure functions are trivially testable and memoisable22const assertEqual = (a, b) => console.log(JSON.stringify(a) === JSON.stringify(b) ? "pass" : "FAIL");23assertEqual(total([{ price: 5, qty: 2 }]), 10); // pass24assertEqual(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.