A pure function is a function that:
- Always returns the same output for the same input
- Does not cause side effects
πΉ Characteristics of Pure Functions
β 1οΈβ£ Deterministic Output
function add(a, b) {
return a + b;
}
Same input → same output β
β 2οΈβ£ No Side Effects
A pure function:
- Does NOT modify external variables
- Does NOT mutate input objects
- Does NOT perform I/O (API calls, DOM changes)
β Impure Function Examples
β Modifies external state
let count = 0;
function increment() {
count++;
}
β Mutates input
function addItem(arr) {
arr.push(5);
}
β Depends on external data
function getTime() {
return new Date();
}
β Pure Version
function addItem(arr) {
return [...arr, 5];
}
π― Why Pure Functions Matter
β Easier to test
β Predictable behavior
β Better performance optimizations
β Foundation of functional programming
β Important in React & Redux
πΉ Pure Functions in React
- Reducers must be pure
React.memorelies on purity- Prevents unexpected re-renders
π― Short Interview Answer
A pure function always produces the same output for the same input and has no side effects. It does not modify external state or depend on external variables, making it predictable and easy to test.
β One-line summary
Pure functions are predictable, side-effect-free functions that always return consistent results.