Skip to main content

Pure Functions

πŸ”Ή Definition​

A Pure Function is a function that:

  1. Given the same input, always returns the same output.
  2. 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?