All topics
Functionsintermediate

Pure Functions and Side Effects

Functions that always return the same output for the same input and don't modify anything outside themselves, versus functions that mutate state or perform I/O.

A pure function is one that, given the same inputs, always produces the same output, and produces no observable side effects — it doesn't mutate external variables, doesn't perform I/O, doesn't modify its arguments, and doesn't rely on anything besides its inputs to compute its result. This concept comes from functional programming, but it matters in everyday JavaScript because pure functions are dramatically easier to test, reason about, memoize, and run in parallel or out of order.

A pure function is like a vending machine that dispenses the exact same snack every time you press the same button, using only the button press as input — no memory of previous purchases, no side conversations with other machines, and pressing the same button twice never changes anyone else's snack.

Key Concepts

1
A function that reads or writes any state outside its own local scope has a side effect: logging to the console, mutating a passed-in object or array, updating a DOM element, making a network request, or reading Date.now()/Math.random() (since these make the output depend on something other than the arguments, breaking the 'same input, same output' guarantee). None of these are forbidden in real applications — side effects are how programs actually do useful things like rendering UI or saving data — but isolating them and keeping the bulk of your logic pure makes the side-effect-free parts trivially testable and reusable.
Date.now()Math.random()
2
A common practical trap is unintentional mutation: a function that looks pure at first glance but calls .push() or .sort() on an argument array actually mutates the caller's data as a side effect, which can introduce bugs far from the function itself when that same array is used elsewhere afterward. Writing the pure version instead — returning a new array via [...array, newItem] or [...array].sort() — avoids this.
.push().sort()[...array, newItem][...array].sort()
3
React's rendering model, Redux reducers, and much of modern frontend architecture lean heavily on pure functions specifically because predictable, side-effect-free transformations make state changes traceable and testable; this is exactly why interviewers ask about purity even outside pure academic functional-programming contexts.