What Makes a Function Pure
You'll learn the two strict requirements a function must meet to be considered "pure" — a key concept in functional programming that makes code predictable and testable.
The Two Golden Rules
A pure function is like a reliable vending machine: you put in the same coins, you always get the same snack, and the machine doesn't randomly redecorate your office while you wait.
In JavaScript, a function is pure when it satisfies both of these conditions:
1. Deterministic Output
The function always returns the same result for the same input arguments. No randomness, no hidden dependencies on external state, no surprises.
// Pure: same input → same output
function add(a, b) {
return a + b;
}
// Not pure: output varies even with same input
function addRandom(a) {
return a + Math.random();
}
2. No Side Effects
The function doesn't modify anything outside itself: no changing variables, no DOM manipulation, no network calls, no logging, no mutating input objects.
// Pure: doesn't change anything outside
function double(num) {
return num * 2;
}
// Not pure: modifies external variable
let count = 0;
function increment() {
count++; // side effect!
return count;
}
Why This Matters
Pure functions are predictable. You can call them a thousand times with the same arguments and trust the result every time. They're easy to test, safe to parallelize, and simple to reason about.
Key Takeaway: A pure function requires both deterministic output (same inputs = same output) and zero side effects (no external changes). These constraints make your code more reliable and easier to debug.