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.

JavaScriptbeginner
10 min read

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:

  1. Deterministic: Given the same arguments, it always returns the same result
  2. No side effects: It does not modify anything outside its own scope
javascriptjavascript
// 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:

javascriptjavascript
// 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
PropertyPure functionImpure function
Same input = same outputAlwaysNot guaranteed
Modifies external stateNeverMay or will
Reads external mutable stateNeverMay or will
Depends only on argumentsYesNo
Has side effectsNoYes
Referentially transparentYesNo

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:

javascriptjavascript
// 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!)
javascriptjavascript
// 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:

javascriptjavascript
// 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 typeExampleWhy it is impure
Mutating external variablescounter++Changes program state outside function
Console outputconsole.log()I/O operation
DOM manipulationdocument.title = "..."Changes browser state
Network requestsfetch(), XMLHttpRequestInteracts with external systems
Mutating argumentsobj.name = "new"Modifies data the caller owns
Random valuesMath.random()Non-deterministic output
Current timeDate.now()Non-deterministic output
Writing to filesfs.writeFileSync()Modifies file system

Pure Functions in Practice

Array Transformation (Pure)

javascriptjavascript
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)

javascriptjavascript
function formatName(firstName, lastName) {
  return `${firstName.trim()} ${lastName.trim()}`.toUpperCase();
}
 
console.log(formatName("  alice  ", " smith ")); // "ALICE SMITH"

Calculation (Pure)

javascriptjavascript
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));  // 45

Object Transformation (Pure)

javascriptjavascript
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)

javascriptjavascript
let discountRate = 0.15;
 
function applyDiscount(price) {
  return price - price * discountRate;
}

After: Pure (Takes State as Argument)

javascriptjavascript
function applyDiscount(price, discountRate) {
  return price - price * discountRate;
}
 
console.log(applyDiscount(100, 0.15)); // 85

Before: Impure (Mutates Argument)

javascriptjavascript
function sortUsers(users) {
  users.sort((a, b) => a.name.localeCompare(b.name)); // mutates original!
  return users;
}

After: Pure (Returns New Array)

javascriptjavascript
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)

javascriptjavascript
function createTimestamp() {
  return Date.now(); // different result every time
}

After: Pure (Accepts Time as Argument)

javascriptjavascript
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:

javascriptjavascript
// 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.keyconst { key, ...rest } = obj

Testing Benefits

Pure functions are trivial to test because they require no setup, mocking, or teardown:

javascriptjavascript
// 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:

javascriptjavascript
// 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 = []; // cleanup

When Impure Functions Are Necessary

Not everything can be pure. These operations are inherently impure and that is acceptable:

javascriptjavascript
// 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

javascriptjavascript
// === 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:

QuestionIf YESIf NO
Does it read external variables?ImpureCould be pure
Does it modify external state?ImpureCould be pure
Does it use Math.random()?ImpureCould be pure
Does it use Date.now()?ImpureCould be pure
Does it do I/O (console, network, DOM)?ImpureCould be pure
Does it mutate its arguments?ImpureCould be pure
All NO answers?Pure-
Rune AI

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
RunePowered by Rune AI

Frequently Asked Questions

Are array methods like map and filter pure?

Yes. `map()`, `filter()`, `reduce()`, `slice()`, and `concat()` do not mutate the original array. They return new arrays. However, `sort()`, `reverse()`, `push()`, `pop()`, `splice()`, `shift()`, and `unshift()` mutate the original array and are impure.

Is console.log a side effect?

Yes. Writing to the console is an I/O operation that changes the observable state of the program's environment. A function that calls `console.log()` is technically impure. In practice, developers often ignore logging when classifying functions, but strictly speaking it is a side effect.

Can a pure function throw an error?

Throwing an error is a form of side effect because it changes the program's control flow in an observable way. Strictly pure functions return values for all valid inputs rather than throwing. In practice, many JavaScript developers write functions that throw for invalid inputs and still consider them "pure enough" for the valid input range.

Should all my functions be pure?

No. A program that does nothing observable is useless. You need impure functions for I/O, DOM updates, network requests, and user interaction. The goal is to maximize the pure core of your logic and confine impurity to well-defined boundaries (event handlers, API routes, render functions).

What is the connection between pure functions and functional programming?

Pure functions are a core principle of functional programming. Functional programming favors immutable data, pure transformations, and function composition. JavaScript is not a purely functional language, but it supports functional patterns well through first-class functions, [arrow functions](/tutorials/programming-languages/javascript/javascript-arrow-functions-a-complete-es6-guide), and array methods.

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.