Skip to main content

Pure function

In short: A pure function is a function that always returns the same result for the same input and has no side effects (it does not change external variables, the DOM, files, the network, etc.).


Detailed explanation

A pure function is a fundamental concept of functional programming. It is predictable, testable, and does not depend on external state.

Two key traits:

  1. Determinism - the same input → always the same output.
  2. No side effects - the function changes nothing outside itself.

Example of a pure function

javascript
function add(a, b) { return a + b; }

Always returns the same result and changes nothing in the outside world.


Example of an impure function

javascript
let counter = 0; function increase() { counter++; // side effect - changes an external variable return counter; }

This function is impure, because its result depends on external state (counter) and it changes that state.


Other examples of impure functions

  • Reading/writing to a file or a database
  • Changing the DOM
  • Calling alert() or console.log()
  • Using random numbers (Math.random())
  • Using the current time (Date.now())

Why pure functions matter

Easy to test - the result depends only on the arguments. Easy to cache (memoization). Safe for parallel execution. Improve the predictability and readability of the code.


Summary

PropertyPure function
Returns the same resultYes
Depends on external variablesNo
Changes external stateNo
ExampleMath.max(1, 5)
OppositeA "dirty" function with side effects

In one phrase:

A pure function is a function that does not affect the outside world and always behaves the same way for the same input.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.