Deterministic Output
A pure function always returns the same output for the same input.
It does not rely on or change external state.
JavaScript Tutorial
Pure functions are predictable: same input, same output, no side effects.
They are the foundation of reliable and testable code.
When functions are pure, debugging becomes easier because behavior is consistent.
They are also safer to reuse and refactor.
function fn(input) { return output; }function add(a, b) {
return a + b;
}
console.log(add(2, 3));No external state, same output for same inputs.
let total = 0;
function addToTotal(amount) {
total += amount;
return total;
}This function changes external state, so it is impure.
A pure function always returns the same output for the same input.
It does not rely on or change external state.
Pure functions do not modify global variables, DOM, or external data.
This makes them easy to test and reason about.
Pure functions are predictable and safe to reuse.
They are ideal for calculations, transformations, and utilities.
function toUpper(words) {
return words.map((w) => w.toUpperCase());
}
console.log(toUpper(["a", "b"]));Input array is not modified, output is new.
function formatPrice(amount) {
return "$" + amount.toFixed(2);
}
console.log(formatPrice(99));Pure utility functions are easy to reuse.
Without
let total = 0;
function add(amount) {
total += amount;
return total;
}With
function add(total, amount) {
return total + amount;
}Return new values instead of modifying parameters.
Pass all required data via parameters.
Avoid logging or IO in functions meant to be pure.
It returns the same result for the same input and has no side effects.
They do not depend on external state.
Modifying a global variable or logging to the console.
Practice: Write a pure function that converts Celsius to Fahrenheit.
// TODO: function toF(c)
One Possible Solution
function toF(c) {
return (c * 9) / 5 + 32;
}
console.log(toF(0));Same inputs produce same output and no side effects.
Not always, but they are easier to test and reuse.
Yes, it interacts with external state.
Try calling the function multiple times with the same input.