Skip to content
jshacks.dev
Fundamentals

JavaScript Interview Question What Is a Pure Function

How to answer what a pure function is: same input gives the same output, with no side effects. See mutation traps, hidden inputs and memoization.

9 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm, Vite and TypeScript logos.

"What is a pure function" is one of the questions where the definition is two sentences and the interview is about the examples. A pure function always returns the same result for the same arguments, and it does nothing else: no changing of outside variables, no modifying its arguments, no reading of the clock or a random number generator, no network or file access. Candidates who stop there get a snippet in return and are asked whether it is pure, and the interesting snippets are the ones that look pure and are not. This post gives the answer in thirty seconds, then the two conditions with code, the traps that hide impurity, why purity matters for testing and caching, how real programs keep the impure parts small, and the wrong answers to avoid. The examples run on Node.js 24.

The answer in thirty seconds

A pure function meets two conditions. First, it is deterministic: given the same arguments, it returns the same value every time, and the value depends on nothing but those arguments. Second, it has no side effects: it does not change anything outside itself, including its arguments. These conditions make a call replaceable by its result, which is called referential transparency, and that is the property that makes pure functions easy to test, cache and reason about.

JavaScript
const add = (a, b) => a + b;

let total = 0;
const addToTotal = (n) => {
  total += n;
  return total;
};

console.log(add(2, 3), add(2, 3));
console.log(addToTotal(2), addToTotal(2));
console.log(total);
Text
5 5
2 4
4

add is pure: the same inputs always give 5, and it touches nothing else. addToTotal fails both conditions. It returns different values for the same input, because it depends on total, and it changes total, which is a side effect visible outside. The second call produced 4 because the first call left a trace.

Condition one: no hidden inputs

A function can depend on things that are not in its parameter list.

JavaScript
function isExpiredImpure(expiresAt) {
  return Date.now() > expiresAt;
}

function isExpiredPure(expiresAt, now) {
  return now > expiresAt;
}

console.log(isExpiredPure(1000, 2000), isExpiredPure(1000, 500));
console.log(isExpiredPure(1000, 2000), isExpiredPure(1000, 2000));

const random = (seed) => (seed * 9301 + 49297) % 233280;
console.log(random(1), random(1));
Text
true false
true true
58598 58598

isExpiredImpure reads the clock, so its answer changes as time passes, and a test of it must either fake the clock or accept a flaky result. Passing now in makes it pure: the same two arguments always give the same answer, and a test can use any date it likes. The same applies to Math.random(), to environment variables and to anything read from a global. A function that needs randomness stays pure if the generator state is passed in and returned, as the small random function does, though most code keeps randomness at the edges.

Condition two: no side effects

The most common side effect is changing an argument.

JavaScript
function addItemImpure(list, item) {
  list.push(item);
  return list;
}

function addItemPure(list, item) {
  return [...list, item];
}

const original = ["a", "b"];

const changed = addItemImpure(original, "c");
console.log(original, changed === original);

const base = ["a", "b"];
const extended = addItemPure(base, "c");
console.log(base, extended, extended === base);
Text
[ 'a', 'b', 'c' ] true
[ 'a', 'b' ] [ 'a', 'b', 'c' ] false

The impure version changed the array that the caller passed in and returned the same array, so original has a new item the caller may not have expected. The pure version built a new array and left the argument alone. Callers can then keep the old value, compare before and after, or share it safely. Other side effects include writing to a variable outside the function, logging, writing a file, sending a request, and changing the DOM.

Array methods that mutate

Knowing which built-in methods change their array is a common follow-up.

JavaScript
const numbers = [3, 1, 2];

const sortedCopy = [...numbers].sort();
console.log(numbers, sortedCopy);

const sortedInPlace = numbers.sort();
console.log(numbers, sortedInPlace === numbers);

const fresh = [3, 1, 2];
console.log(fresh.toSorted(), fresh.toReversed(), fresh.with(0, 9), fresh);
Text
[ 3, 1, 2 ] [ 1, 2, 3 ]
[ 1, 2, 3 ] true
[ 1, 2, 3 ] [ 2, 1, 3 ] [ 9, 1, 2 ] [ 3, 1, 2 ]

sort(), reverse(), push(), pop(), shift(), unshift() and splice() change the array they are called on. map(), filter(), slice(), concat() and the spread operator return new arrays. The methods toSorted(), toReversed(), toSpliced() and with(), available in Node.js 20 and later, are copying versions of the mutating ones, and the last line shows fresh unchanged after all three. A pure function that needs a sorted result copies first or uses toSorted().

The shallow copy trap

A copy made with spread is one level deep, and nested objects are still shared.

JavaScript
function renameImpure(user, name) {
  const copy = { ...user };
  copy.profile.name = name;
  return copy;
}

function renamePure(user, name) {
  return { ...user, profile: { ...user.profile, name } };
}

const user = { id: 1, profile: { name: "Ada" } };

const broken = renameImpure(user, "Grace");
console.log(user.profile.name, broken === user, broken.profile === user.profile);

const second = { id: 1, profile: { name: "Ada" } };
const fixed = renamePure(second, "Grace");
console.log(second.profile.name, fixed.profile.name, fixed.profile === second.profile);
Text
Grace false true
Ada Grace false

The first function copied the outer object and still changed the original, because copy.profile and user.profile are the same object. It looks pure, since it returns a new object, and it has a side effect. The fix is to copy every level that changes, as the second function does. For deeply nested data, structuredClone() copies everything, at a cost, and update libraries such as Immer let you write mutation-style code that produces new objects.

Enforcing purity with freezing

Object.freeze() turns accidental mutation into an error, which makes impurity visible in tests.

JavaScript
"use strict";

const frozen = Object.freeze(["a", "b"]);

try {
  frozen.push("c");
} catch (e) {
  console.log(e.name, "-", e.message);
}

try {
  frozen[0] = "z";
} catch (e) {
  console.log(e.name, "-", e.message);
}

console.log(addItemPure(frozen, "c"));

const shallow = Object.freeze({ list: [1] });
shallow.list.push(2);
console.log(shallow.list);
Text
TypeError - Cannot add property 2, object is not extensible
TypeError - Cannot assign to read only property '0' of object '[object Array]'
[ 'a', 'b', 'c' ]
[ 1, 2 ]

Freezing an input in a test shows whether a function mutates it: the impure version would throw. The pure function from earlier works on the frozen array without complaint. The last two lines show the limit: freeze is shallow, so the nested array can still be changed. A deep freeze helper, or a persistent data library, is needed for nested data. The directive at the top is redundant in a module, and is there to say strict mode is on, which is what turns the failed write into an error.

Why purity matters

The practical benefits are the points to make after the definition.

JavaScript
function memoize(fn) {
  const cache = new Map();
  return (arg) => {
    if (!cache.has(arg)) cache.set(arg, fn(arg));
    return cache.get(arg);
  };
}

const square = memoize((n) => n * n);
console.log(square(4), square(4));

let rate = 2;
const scale = memoize((n) => n * rate);
console.log(scale(10));
rate = 3;
console.log(scale(10));
Text
16 16
20
20

A pure function can be cached, because its result depends only on its argument: square(4) is 16 now and always. The impure scale reads an outside variable, so after rate changed, the cache returned the stale 20 where the right answer was 30. Pure functions are also easy to test, since a test needs no setup and no cleanup, and safe to run in parallel, since they share no state. They compose: the output of one is a valid input to the next.

Real programs need side effects

A program with no side effects does nothing observable, so the goal is to keep them at the edges. A common structure is a functional core that computes decisions from data, and a thin shell that reads input and carries out the results.

JavaScript
function planDiscount(order) {
  const subtotal = order.items.reduce((sum, item) => sum + item.price * item.qty, 0);
  const rate = subtotal >= 100 ? 0.1 : 0;
  return { subtotal, discount: subtotal * rate, total: subtotal * (1 - rate) };
}

const order = { items: [{ price: 40, qty: 2 }, { price: 30, qty: 1 }] };

const plan = planDiscount(order);
console.log(plan);
console.log(JSON.stringify(plan) === JSON.stringify(planDiscount(order)));
Text
{ subtotal: 110, discount: 11, total: 99 }
true

planDiscount is pure and does all the thinking: it can be tested with plain objects. A separate function would read the order from the database and save the result, and would contain no business logic. That split is what interviewers mean when they ask where side effects go: in a small outer layer that calls pure functions with the data it fetched.

Wrong answers that lose the point

  • "A pure function cannot use outside variables." It can read constants and other pure functions; it cannot depend on values that change.

  • "console.log is fine." Technically it is a side effect, though harmless in practice; strict definitions count it.

  • "Pure functions cannot use loops or let." Local mutation that nobody can observe is allowed.

  • "Returning a new object makes a function pure." It must also not change its arguments or anything outside, as the shallow copy example showed.

A mistake we hit: a pure-looking reducer that mutated

JavaScript
function reducer(state, action) {
  if (action.type === "add") {
    state.items.push(action.item);
    return { ...state };
  }
  return state;
}

const before = { items: ["a"] };
const after = reducer(before, { type: "add", item: "b" });

console.log(before.items, after.items);
console.log(before === after, before.items === after.items);
Text
[ 'a', 'b' ] [ 'a', 'b' ]
false true

The reducer returned a new top-level object, so a check of before === after said the state changed, but the items array was the same one, mutated in place. A history of previous states, which relies on old states staying intact, would show the new item in every earlier entry. We found it when an undo feature did nothing. The fix is { ...state, items: [...state.items, action.item] }. A frozen state in tests would have caught it on the first run.

Choosing between the styles

You haveDo this
A calculation from inputsWrite a pure function
Needs the time or randomnessPass them in as arguments
An array operation on a shared arrayCopy first, or use toSorted(), map(), filter()
Nested data to updateCopy each changed level, or use an update library
I/O, logging, the DOMKeep it in a thin outer layer
Doubt about a functionFreeze its inputs in a test

Practical rules we follow

Pass in everything a function needs, including the time. Return new values and leave arguments alone. Copy every level you change. Freeze inputs in tests. Keep side effects at the edges, and keep the logic in pure functions that the edges call. Memoize only pure functions. And when asked in an interview, give the two conditions, then an example of each way a function can fail them.

Where the pure function answer stops being enough

A deeper question covers referential transparency and equational reasoning, immutable data structures and structural sharing, how React and Redux depend on purity, and the idea of effects as data in languages that track them in the type system. JavaScript does not enforce purity, so it is a discipline. The reference is in the MDN glossary entry for pure functions and the [MDN page on Object.freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze).

Taggedinterview
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.