Lesson 28 of 80
A pure function's output depends only on its input, and never changes anything outside itself — the property that makes code testable, predictable, and safe to memoize.
12 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
Which of these two is a pure function: `(cart, item) => { cart.push(item); return cart; }` or `(cart, item) => [...cart, item]`?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
A function is pure if it satisfies two rules: given the same input, it always returns the same output, and it causes no side effects — it doesn't mutate arguments, doesn't touch outside variables, doesn't log, fetch, or write.
// impure — mutates its argument, a side effect
function addItemImpure(cart, item) {
cart.push(item);
return cart;
}
// pure — same inputs always give the same new array, original untouched
function addItemPure(cart, item) {
return [...cart, item];
}
Immutability is the discipline that makes purity practical: instead of changing a value in place, you produce a new value with the change applied, leaving the original untouched.
state.items.push(x) — mutates the array in place. Same reference as before.
setState({ ...state, loading: true }) instead of state.loading = true — React compares references to decide whether to re-render; mutating in place doesn't change the reference, so React can miss the update entirely.Object.freeze only freezes one level; nested objects inside a frozen object are still fully mutable unless you freeze them too, or use a library that deep-freezes."Why does mutating state directly sometimes not trigger a re-render in React?" is a very common real bug, and the honest root cause is this lesson: React relies on reference equality, which mutation doesn't change.