Pure Functions
πΉ Definitionβ
A Pure Function is a function that:
- Given the same input, always returns the same output.
- Has no side effects (doesnβt modify variables, objects, or states outside of its scope).
πΉ Characteristics of Pure Functionsβ
- Deterministic β Same input β Same output.
- No side effects β Doesnβt modify external variables, objects, databases, or DOM.
- Self-contained β Only depends on its arguments, not external state.
πΉ Examplesβ
β Pure Function Exampleβ
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
console.log(add(2, 3)); // 5 (always the same result)
π Same input (2,3) will always give 5.
β Impure Function Example (side effect)β
let total = 0;
function addToTotal(a) {
total += a; // modifies external variable
return total;
}
console.log(addToTotal(5)); // 5
console.log(addToTotal(5)); // 10 (different result for same input)
π Depends on external state (total), so itβs not pure.
β Impure Function Example (randomness)β
function getRandomNumber() {
return Math.random();
}
console.log(getRandomNumber()); // e.g. 0.123
console.log(getRandomNumber()); // e.g. 0.984
π Same input (none), but different outputs each time β impure.
πΉ Real-World Exampleβ
Pure Function (Safe for financial calculations)β
function calculateTax(amount, taxRate) {
return amount * taxRate;
}
console.log(calculateTax(1000, 0.2)); // 200
console.log(calculateTax(1000, 0.2)); // 200 (consistent)
Impure Function (Not safe)β
let taxRate = 0.2;
function calculateTaxImpure(amount) {
taxRate = taxRate + 0.01; // modifies global state
return amount * taxRate;
}
console.log(calculateTaxImpure(1000)); // 210
console.log(calculateTaxImpure(1000)); // 220 (different!)
πΉ Why Pure Functions Matter?β
- β Easier to test (no dependencies on external state).
- β Easier to debug (predictable behavior).
- β Useful in functional programming & frameworks like React (pure components).
- β Help in immutability and avoiding bugs.
π Would you like me to also explain how React components follow the idea of pure functions (like render() being pure) with examples?