Skip to the solution
MediumFrontend7 min read

What is a pure function?

132 views

The problem

Question presented to candidate: "What makes a function pure, and why does that property matter in practice?"

What a strong answer should cover:

  • A pure function must satisfy two conditions: the same input always produces the same output (determinism), and it causes no observable side effects (no mutating arguments, no mutating outer/global state, no I/O, no relying on non-deterministic input like Math.random or the current time).
  • Purity is a property of the function's OWN logic, not its inputs -- a function that mutates an object it was passed is impure even if the caller never notices, because the mutation is an observable side effect.
  • Pure functions are trivially testable (no setup/teardown, no mocking), safely memoizable (same input always yields the cached output), and safe to run in parallel or reorder, since they cannot interfere with anything outside themselves.
  • Most real programs cannot be 100% pure everywhere -- I/O, rendering, and state updates are inherently impure -- so the practical goal is usually to push impurity to the edges and keep as much core logic pure as possible.
  • A function returning a NEW object/array instead of mutating the one it received is the most common way to keep transformation logic pure in JavaScript.

Code / implementation expected: Yes -- a runnable snippet contrasting a pure and an impure version of the same operation, with real observed output showing the impure version produce different results for identical input.

  • pure-functions

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read Β· 7 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptPure vs impure: determinism (run directly)
JavaScriptPure vs impure: mutation of an argument (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 115 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What is a higher-order function?

Continue