What are Pure Functions?
A pure function is a function where the return value is determined only by its input values, without observable side effects.
Pure functions have two key characteristics: 1) Given the same input, they always return the same output, and 2) They don't modify anything outside their scope.
Pure vs Impure Functions
// PURE FUNCTION - same input always gives same output
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
console.log(add(2, 3)); // 5 - always the same
// IMPURE FUNCTION - depends on external state
let globalMultiplier = 2;
function multiplyImpure(x) {
return x * globalMultiplier; // depends on global variable
}
console.log(multiplyImpure(5)); // 10
globalMultiplier = 3;
console.log(multiplyImpure(5)); // 15 - different output!
// PURE FUNCTION - takes multiplier as parameter
function multiplyPure(x, multiplier) {
return x * multiplier;
}
console.log(multiplyPure(5, 2)); // 10
console.log(multiplyPure(5, 2)); // 10 - always the samePure functions are predictable and testable because their output depends only on their inputs.