A function is pure when two things hold:
- Same inputs, same output. The result depends only on the arguments — not on mutable outer variables, the clock (
Date.now()), randomness (Math.random()), the DOM or the network. - No side effects. It doesn't change anything that existed before it was called: no writing to arguments or outer variables, no logging, no requests, no timers.
Mutating local state is fine. A function can build an array with push inside its own body and still be pure, because nobody else can observe it.
Why it matters:
- Referential transparency. A call can be replaced by its value, so results can be cached (memoization) and calls skipped, repeated or reordered without changing behaviour.
- Testing. Pass inputs, assert the output; no mocks or setup.
- Change detection. Code that compares by reference — React state, memoised selectors — relies on updates returning new objects instead of mutating old ones.
- Re-runs. React requires components to be pure and, in development Strict Mode, calls each component function twice to surface components that aren't.
JavaScript has no purity marker and no compiler check, and objects are passed by sharing, so any function that receives an object can mutate it. Some built-ins mutate their receiver: sort, reverse, splice, fill. ES2023 added copying versions — toSorted, toReversed, toSpliced, with — so the pure form no longer needs a manual copy.
Real programs need effects, so the goal isn't to remove them. It's to keep the core computation pure and push effects (I/O, state writes, logging) to the edges, like event handlers, where they're explicit and few.