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:
- Determinism - the same input → always the same output.
- No side effects - the function changes nothing outside itself.
Example of a pure function
function add(a, b) {
return a + b;
}Always returns the same result and changes nothing in the outside world.
Example of an impure function
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()orconsole.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
| Property | Pure function |
|---|---|
| Returns the same result | Yes |
| Depends on external variables | No |
| Changes external state | No |
| Example | Math.max(1, 5) |
| Opposite | A "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 readyA concise answer to help you respond confidently on this topic during an interview.