As you dive deeper into JavaScript and functional programming, you'll hear a lot about pure functions. But what exactly makes a function _pure_, and why do developers care so much about them?
In this post, we'll break down what pure functions are, why they matter, and how to write them in JavaScript.
đź§Ľ What is a pure function?
A pure function is a function that, given the same inputs, will _always_ return the same output and has no side effects.
In other words:
- âś… It doesn't change anything outside itself (no modifying global variables, DOM, or arguments)
- âś… It only depends on the inputs you give it
- ✅ It’s predictable and testable
đźš« Impure vs âś… pure function example
Let’s compare:
Impure function:
let counter = 0;
function increment() {
counter++;
return counter;
}
- ❌ Depends on external state (
counter
) - ❌ Modifies that state
- ❌ Not predictable from just looking at the inputs
Pure function:
function add(a, b) {
return a + b;
}
- âś… Only depends on
a
andb
- ✅ Doesn’t change anything outside
- âś… Same input = same output, every time
🔍 Why use pure functions?
Pure functions make your code:
- Easier to test — no hidden state
- Easier to debug — you know where things went wrong
- Easier to reuse — they're self-contained
- Safer for concurrency — no shared mutable state
They also play a big role in functional programming and libraries like Redux or RxJS.
🎯 Real-world example
Let’s say you want to apply a discount:
// Pure
function applyDiscount(price, percentage) {
return price - price * (percentage / 100);
}
// Impure
let globalTax = 5;
function applyTax(price) {
return price + price * (globalTax / 100);
}
The pure version is easier to reason about and reuse. The impure version depends on globalTax
, which could change.
⚠️ Common pitfall: mutating inputs
Even if you don’t use globals, mutating the function’s input still breaks purity:
function double(numbers) {
for (let i = 0; i < numbers.length; i++) {
numbers[i] *= 2;
}
return numbers;
}
This mutates the original array. Instead, return a new one:
function double(numbers) {
return numbers.map(n => n * 2);
}
✅ Now it’s pure.
âś… Recap
- A pure function:
- Always gives the same output for the same input
- Has no side effects
- Avoid global state and mutations
- Pure functions are easier to test, debug, and maintain
📌 Conclusion
Pure functions are a small but powerful concept in JavaScript. They help you write code that’s predictable, modular, and easier to work with—especially in large or complex applications.
Start simple: avoid side effects, don't mutate data, and focus on writing functions that do one thing well. Your future self (and teammates) will thank you.