Skip to main content

Pure Function

A pure function returns the same output for the same input with no side effects, making it easy to test, cache, and run concurrently.

A pure function is a function whose result depends only on its inputs and which causes no observable side effects. Given the same arguments, it always produces the same return value, and it does not modify external state, perform I/O, mutate its inputs, or otherwise interact with the world beyond returning a value.

How It Works

Two properties define purity. First, deterministic output: the function maps inputs to outputs the same way every time, so it cannot depend on the clock, random numbers, global variables, or external data. Second, no side effects: it does not write files, send network calls, update databases, or change variables outside its scope. A function that computes a discount from a price and a rate is pure; one that also logs the result or reads a global tax setting is not. Real programs need side effects, so a common design pushes impurity to the edges and keeps the core logic pure.

Why It Matters

Pure functions are exceptionally easy to test: pass inputs, assert outputs, with no setup or mocking. They are safe to call concurrently because they share no mutable state, and their results can be cached (memoized) since they never change for the same input. They also compose cleanly and make code easier to reason about, because their behavior is fully captured by their signature.

The limitation is that pure functions alone cannot do useful work like saving data; they must be combined with controlled impure code at the boundaries.

Related Terms

Immutability is closely tied to purity. Concurrency benefits from pure code's lack of shared state. Unit tests are trivial for pure functions, and dependency injection helps isolate impurity.