What Is a Pure Function? Same Input, Same Output
A pure function always returns the same output for the same input and causes no observable side effects, so it depends on nothing but its arguments.
Purity is a simple, powerful property. A pure function is fully determined by its inputs: give it the same arguments and it always returns the same result, and running it changes nothing else in the program. No reading the clock, no writing to disk, no mutating shared state. That predictability makes pure functions the easiest code to test and reason about.
The two rules of purity
A function is pure if (1) its return value depends only on its inputs, and (2) it produces no side effects, no mutation of external state, no I/O, no randomness. Break either rule and the function is impure.
Why purity matters
- Trivial to test: no setup, no mocks, just inputs and expected outputs.
- Safe to cache (memoize), since the result never varies for given inputs.
- Safe to run in parallel, with no shared state to race over.
- Easy to reason about, because nothing hidden affects the result.
Pure vs impure
Real programs need side effects (saving data, calling APIs), so not everything can be pure. The common pattern is to keep a pure core of logic and push impure effects to the edges, where they are easier to control and test.
Purity and determinism
Pure functions are deterministic, which is exactly what reliable tests want. Tests that depend on the clock, randomness, or network calls are impure and tend to flake. Isolating impurity is a direct path to stable test suites.
A quick example
A function add(a, b) => a + b is pure: same inputs always give the same output, and it touches nothing else. A function that returns Date.now() is impure, since its output changes over time.
Pure functions in CI
Tests over pure functions are deterministic and rarely flake, so a failure is a real bug worth surfacing, not retrying. Latchkey auto-retries transient infrastructure failures but lets genuine, repeatable test failures stand so they are not hidden.
Key takeaways
- A pure function returns the same output for the same input and has no side effects.
- Purity makes code easy to test, cache, parallelize, and reason about.
- Pushing side effects to the edges yields a deterministic, low-flake test suite.