Pure Functions
Pure Functions
Section titled “Pure Functions”Introduction
Section titled “Introduction”A pure function is a function that:
- Returns the same output for the same input (deterministic)
- Has no side effects (doesn’t modify external state)
Why Do We Need This?
Section titled “Why Do We Need This?”Pure functions are predictable, testable, and safe to use in concurrent environments. They are fundamental to functional programming.
Visual Explanation
Section titled “Visual Explanation”flowchart LR Input["Input: 5"] --> Pure["Pure Function: double(x)"] Pure --> Output["Output: 10"]
Input2["Input: 5"] --> Pure Pure --> Output2["Output: 10"]
Input3["Input: 5"] --> Pure Pure --> Output3["Output: 10"]
style Pure fill:#4CAF50Pure vs Impure
Section titled “Pure vs Impure”// ✅ Pure — no side effectsfunction add(a, b) { return a + b;}
// ❌ Impure — modifies external statelet total = 0;function addToTotal(value) { total += value;}
// ✅ Pure — same input = same outputfunction greet(name) { return `Hello, ${name}!`;}
// ❌ Impure — depends on external statefunction greetUser() { return `Hello, ${userName}!`; // userName is external}Benefits
Section titled “Benefits”// ✅ Easy to testfunction double(x) { return x * 2; }// Test: double(2) always returns 4
// ✅ Cacheable (memoization)const memoized = (() => { const cache = {}; return (n) => { if (cache[n] !== undefined) return cache[n]; cache[n] = double(n); return cache[n]; };})();
// ✅ Parallel safe — no shared stateSummary
Section titled “Summary”- Pure functions: same input → same output, no side effects
- Easy to test, cache, and reason about
- Prefer pure functions for predictable code
- Use impure functions only when necessary (IO, state changes)