As applications grow, unpredictable behavior becomes the biggest enemy.
Pure functions help eliminate uncertainty by enforcing **consistency**.
They are a foundational concept in clean and functional JavaScript.
## 🔹 What Is a Pure Function?
A function is pure if:
1. It always returns the same output for the same input
2. It does not modify external state
3. It has no side effects
## 🔹 Side Effects Explained
Side effects include:
- Modifying global variables
- Changing objects passed by reference
- Making API calls
- Logging to the console
These make code harder to reason about.
## 🔹 Impure Function Example
```js
let taxRate = 0.1;
function calculateTax(amount) {
return amount * taxRate;
}
The result depends on external state.
🔹 Pure Function Version
function calculateTax(amount, taxRate) {
return amount * taxRate;
}
Now the function is predictable.
🔹 Why Pure Functions Are Powerful
Pure functions:
• Are easier to test
• Can be safely reused
• Work well with immutability
• Enable memoization
🔹 Pure Functions and Arrays
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
map returns a new array without modifying the original.
🔹 Common Mistakes
❌ Mutating arguments
❌ Relying on globals
❌ Mixing logic with effects
🔹 When Impure Functions Are OK
Impurity is unavoidable when:
• Reading user input
• Writing to the DOM
• Fetching data
Best practice:
➡️ Isolate impurity at the edges
🔹 Best Practices
• Keep core logic pure
• Pass dependencies as parameters
• Separate logic from effects
✅ Recommended:
const total = calculateTotal(items, taxRate);