Pure vs Impure Functions in JavaScript Explained
Learn the difference between pure and impure functions in JavaScript. Covers referential transparency, side effects, mutable vs immutable data, testing benefits, and when to use each pattern in real-world applications.
A pure function always returns the same output for the same input and produces no side effects. An impure function might return different results for identical inputs, modify external state, or interact with the outside world. Understanding this distinction is foundational for writing predictable, testable, and maintainable JavaScript code.
This tutorial explains what makes a function pure or impure, demonstrates each with practical examples, covers the testing advantages of pure functions, and shows when impure functions are necessary and acceptable.
What is a Pure Function?
A pure function has exactly two properties:
- Deterministic: Given the same arguments, it always returns the same result
- No side effects: It does not modify anything outside its own scope
// Pure function: same input = same output, no side effects
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5 (always)
console.log(add(2, 3)); // 5 (always)
console.log(add(2, 3)); // 5 (always)Referential Transparency
A pure function call can be replaced with its return value without changing program behavior. This property is called referential transparency:
// These two lines are equivalent because add is pure
const result = add(2, 3) * add(4, 5);
const result = 5 * 9; // same behavior, no observable difference| Property | Pure function | Impure function |
|---|---|---|
| Same input = same output | Always | Not guaranteed |
| Modifies external state | Never | May or will |
| Reads external mutable state | Never | May or will |
| Depends only on arguments | Yes | No |
| Has side effects | No | Yes |
| Referentially transparent | Yes | No |
What is an Impure Function?
An impure function breaks one or both rules. It either produces different outputs for the same inputs, causes side effects, or both:
// Impure: reads external mutable state
let taxRate = 0.08;
function calculateTotal(price) {
return price + price * taxRate; // depends on external variable
}
console.log(calculateTotal(100)); // 108
taxRate = 0.10;
console.log(calculateTotal(100)); // 110 (different result, same input!)// Impure: modifies external state (side effect)
let counter = 0;
function increment() {
counter++; // modifies variable outside its scope
return counter;
}
console.log(increment()); // 1
console.log(increment()); // 2 (different result each time)Common Side Effects
Side effects are any observable changes to the world outside the function:
// Side effect: modifying an external variable
let total = 0;
function addToTotal(amount) {
total += amount; // modifies external state
}
// Side effect: writing to console
function logUser(user) {
console.log(user.name); // I/O operation
return user;
}
// Side effect: modifying the DOM
function updateTitle(title) {
document.title = title; // modifies browser state
}
// Side effect: making a network request
async function saveUser(userData) {
await fetch("/api/users", { method: "POST", body: JSON.stringify(userData) });
}
// Side effect: modifying a function argument (mutation)
function addId(user) {
user.id = Math.random(); // mutates the passed object
return user;
}| Side effect type | Example | Why it is impure |
|---|---|---|
| Mutating external variables | counter++ | Changes program state outside function |
| Console output | console.log() | I/O operation |
| DOM manipulation | document.title = "..." | Changes browser state |
| Network requests | fetch(), XMLHttpRequest | Interacts with external systems |
| Mutating arguments | obj.name = "new" | Modifies data the caller owns |
| Random values | Math.random() | Non-deterministic output |
| Current time | Date.now() | Non-deterministic output |
| Writing to files | fs.writeFileSync() | Modifies file system |
Pure Functions in Practice
Array Transformation (Pure)
function doubleAll(numbers) {
return numbers.map((n) => n * 2); // returns new array, does not mutate
}
const original = [1, 2, 3, 4];
const doubled = doubleAll(original);
console.log(original); // [1, 2, 3, 4] (unchanged)
console.log(doubled); // [2, 4, 6, 8]String Processing (Pure)
function formatName(firstName, lastName) {
return `${firstName.trim()} ${lastName.trim()}`.toUpperCase();
}
console.log(formatName(" alice ", " smith ")); // "ALICE SMITH"Calculation (Pure)
function calculateDiscount(price, discountPercent) {
const discount = price * (discountPercent / 100);
return Math.max(price - discount, 0); // never returns negative
}
console.log(calculateDiscount(100, 20)); // 80
console.log(calculateDiscount(50, 10)); // 45Object Transformation (Pure)
function updateUserEmail(user, newEmail) {
// Returns a new object, does not mutate the original
return { ...user, email: newEmail };
}
const user = { name: "Alice", email: "old@example.com" };
const updated = updateUserEmail(user, "new@example.com");
console.log(user.email); // "old@example.com" (unchanged)
console.log(updated.email); // "new@example.com"Spread Creates New Objects
The spread operator { ...obj } creates a shallow copy. This is the standard pattern for returning modified objects from pure functions without mutating the original.
Making Impure Functions Purer
Before: Impure (Reads External State)
let discountRate = 0.15;
function applyDiscount(price) {
return price - price * discountRate;
}After: Pure (Takes State as Argument)
function applyDiscount(price, discountRate) {
return price - price * discountRate;
}
console.log(applyDiscount(100, 0.15)); // 85Before: Impure (Mutates Argument)
function sortUsers(users) {
users.sort((a, b) => a.name.localeCompare(b.name)); // mutates original!
return users;
}After: Pure (Returns New Array)
function sortUsers(users) {
return [...users].sort((a, b) => a.name.localeCompare(b.name));
}
const original = [{ name: "Charlie" }, { name: "Alice" }, { name: "Bob" }];
const sorted = sortUsers(original);
console.log(original[0].name); // "Charlie" (unchanged)
console.log(sorted[0].name); // "Alice"Before: Impure (Uses Date.now)
function createTimestamp() {
return Date.now(); // different result every time
}After: Pure (Accepts Time as Argument)
function createTimestamp(currentTime) {
return currentTime;
}
// The impurity is pushed to the caller
const timestamp = createTimestamp(Date.now());Mutation vs Immutability
Pure functions depend on immutability. JavaScript arrays and objects are mutable by default, so you must be intentional:
// IMPURE: mutates the original array
function addItem(list, item) {
list.push(item);
return list;
}
// PURE: creates a new array
function addItem(list, item) {
return [...list, item];
}
// IMPURE: mutates the original object
function updateAge(person, newAge) {
person.age = newAge;
return person;
}
// PURE: creates a new object
function updateAge(person, newAge) {
return { ...person, age: newAge };
}Immutable Operations Reference
| Mutable (impure) | Immutable (pure) |
|---|---|
arr.push(item) | [...arr, item] |
arr.pop() | arr.slice(0, -1) |
arr.splice(i, 1) | arr.filter((_, idx) => idx !== i) |
arr.sort() | [...arr].sort() |
arr.reverse() | [...arr].reverse() |
obj.key = value | { ...obj, key: value } |
delete obj.key | const { key, ...rest } = obj |
Testing Benefits
Pure functions are trivial to test because they require no setup, mocking, or teardown:
// Pure function
function calculateShipping(weight, distance) {
const baseRate = 5;
const weightRate = weight * 0.5;
const distanceRate = distance * 0.1;
return baseRate + weightRate + distanceRate;
}
// Tests are simple: input -> expected output
console.assert(calculateShipping(10, 100) === 20, "10kg, 100km");
console.assert(calculateShipping(0, 0) === 5, "minimum shipping");
console.assert(calculateShipping(20, 50) === 20, "20kg, 50km");Compare with testing an impure function:
// Impure function: requires setup and cleanup
let shippingLog = [];
function calculateAndLogShipping(weight, distance) {
const cost = 5 + weight * 0.5 + distance * 0.1;
shippingLog.push({ weight, distance, cost }); // side effect
return cost;
}
// Test requires cleanup
shippingLog = []; // setup
calculateAndLogShipping(10, 100);
console.assert(shippingLog.length === 1, "logged one entry");
shippingLog = []; // cleanupWhen Impure Functions Are Necessary
Not everything can be pure. These operations are inherently impure and that is acceptable:
// Database operations
async function saveUser(user) {
return await db.collection("users").insertOne(user);
}
// DOM updates
function renderList(items) {
const ul = document.createElement("ul");
items.forEach((item) => {
const li = document.createElement("li");
li.textContent = item;
ul.appendChild(li);
});
document.body.appendChild(ul);
}
// Logging
function logError(error) {
console.error(`[${new Date().toISOString()}] ${error.message}`);
}Push Impurity to the Edges
The best pattern is to keep your core logic pure and push side effects to the outer edges of your application. Pure functions handle calculations, transformations, and decisions. Impure functions at the boundaries handle I/O, DOM updates, and network requests.
The Pure Core, Impure Shell Pattern
// === PURE CORE ===
function validateOrder(order) {
const errors = [];
if (!order.items.length) errors.push("Order must have items");
if (order.total <= 0) errors.push("Total must be positive");
return { isValid: errors.length === 0, errors };
}
function calculateOrderTotal(items) {
return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
function formatReceipt(order, total) {
return {
orderId: order.id,
items: order.items.map((i) => `${i.name} x${i.quantity}`),
total: `$${total.toFixed(2)}`,
};
}
// === IMPURE SHELL ===
async function processOrder(order) {
const total = calculateOrderTotal(order.items); // pure
const validation = validateOrder({ ...order, total }); // pure
if (!validation.isValid) {
console.error("Validation failed:", validation.errors); // impure (logging)
return;
}
const receipt = formatReceipt(order, total); // pure
await saveToDatabase(receipt); // impure (I/O)
sendConfirmationEmail(order.email, receipt); // impure (I/O)
}Quick Reference: Identifying Pure vs Impure
Ask these questions about any function declaration:
| Question | If YES | If NO |
|---|---|---|
| Does it read external variables? | Impure | Could be pure |
| Does it modify external state? | Impure | Could be pure |
Does it use Math.random()? | Impure | Could be pure |
Does it use Date.now()? | Impure | Could be pure |
| Does it do I/O (console, network, DOM)? | Impure | Could be pure |
| Does it mutate its arguments? | Impure | Could be pure |
| All NO answers? | Pure | - |
Rune AI
Key Insights
- Same input, same output: pure functions are deterministic and predictable
- No side effects: pure functions do not modify external state, do I/O, or mutate arguments
- Use immutable patterns:
[...arr],{ ...obj },map(),filter()instead of mutating methods - Push impurity to edges: pure core for logic, impure shell for I/O and DOM
- Testing is trivial: no mocks, no setup, no cleanup for pure functions
- Not everything can be pure: DOM updates, API calls, and logging are inherently impure
Frequently Asked Questions
Are array methods like map and filter pure?
Is console.log a side effect?
Can a pure function throw an error?
Should all my functions be pure?
What is the connection between pure functions and functional programming?
Conclusion
Pure functions return the same output for the same input and cause no side effects. Impure functions modify external state, depend on mutable data, or interact with the outside world through I/O. Pure functions are easier to test, reason about, debug, and compose. The practical approach is not to make everything pure, but to keep your core logic in pure functions and push side effects (DOM, network, logging) to the outer edges of your application. Use immutable patterns (spread operator, map, filter) to avoid accidental mutation.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.