What is a pure function?
A pure function, given the same inputs, always returns the same output and has no side effects.
Two rules:
Deterministic — same input → same output, every time. It depends only on its arguments, not on external state.
No side effects — it doesn't change anything outside itself (no mutating external variables, no DOM changes, no API calls, no logging).
Why they matter: pure functions are predictable, easy to test, and safe to cache.
// Pure functions
function add(a, b) { return a + b; } // Same input → same output
function toUpper(str) { return str.toUpperCase(); } // No side effects
const double = arr => arr.map(x => x * 2); // New array, no mutation
// Impure functions
let total = 0;
function addToTotal(n) { total += n; return total; } // Modifies external state
function getRandomId() { return Math.random(); } // Non-deterministic
function saveUser(user) { db.save(user); } // Side effect (I/O)
function sortArray(arr) { return arr.sort(); } // Mutates the input!
// Making impure → pure
// Impure: mutates input
function addItem(list, item) { list.push(item); return list; }
// Pure: returns new array
function addItemPure(list, item) { return [...list, item]; }add and toUpper are pure: deterministic, no side effects. addToTotal modifies external total (impure). getRandomId is non-deterministic (impure). arr.sort() mutates the input array (impure). The fix: return a new array with spread instead of mutating.
Two rules: same input = same output, no side effects. Show examples of both pure and impure functions.
The array sort mutation gotcha (sort modifies in place) is commonly tested. Know that array.sort() is impure — use [...arr].sort() or toSorted().