Skip to content
Velloreth
Programming 7 min read

Pure Functions and Side Effects Explained

A pure function returns the same output for the same input and changes nothing outside itself. Learn why that matters and how to manage side effects.

By

What purity means

A pure function has exactly two properties:

  1. Deterministic — the same arguments always produce the same return value.
  2. No side effects — it does not modify anything outside itself.

That is the whole definition. Both properties matter, and both are easy to violate accidentally.

// Pure
function add(a, b) {
  return a + b;
}

// Impure: depends on external state
let taxRate = 0.13;
function withTax(price) {
  return price * (1 + taxRate); // changes if taxRate changes
}

// Impure: mutates its argument
function addItem(cart, item) {
  cart.push(item); // caller's array is modified
  return cart;
}

// Impure: reads the clock
function timestamp() {
  return Date.now();
}

The first function is pure. The other three are not, for three different reasons: external state, mutation, and non-determinism.

Why purity matters

Purity is not an aesthetic preference. It has concrete engineering consequences.

Testing is trivial. A pure function needs no mocks, no fixtures, no database, and no clock. You call it and check the result.

// Testing a pure function
expect(withTaxPure(100, 0.13)).toBe(113);

Compare that with testing an impure version, where you must set up the global, run the test, and reset it afterwards — and where test order can change the outcome.

Results can be cached. If the same input always gives the same output, you can memoise freely. This is the basis of dynamic programming and of every memoisation cache.

Calls can be reordered or parallelised. Pure calls do not interfere with each other, so a runtime can evaluate them in any order or concurrently. Impure calls cannot be reordered without changing behaviour.

Reasoning is local. To understand a pure function you read only that function. To understand an impure one you must also understand everything it touches.

Refactoring is safe. You can extract, inline, or move a pure function without worrying about what breaks.

Side effects are not the enemy

It is worth being clear: a program with no side effects does nothing. Reading input, writing output, saving to a database, sending a request, updating the screen — all are side effects, and all are necessary.

The problem is not side effects. The problem is side effects scattered through logic, where they make the logic hard to test and hard to reason about.

The goal is to isolate them, not eliminate them.

The functional core, imperative shell

This is the pattern that makes purity practical. Split the program in two:

  • Functional core — pure functions that make all the decisions. No I/O, no mutation, no clock.
  • Imperative shell — a thin layer that performs all the effects and calls into the core.
// ---- Functional core: pure decisions ----

function calculateDiscount(cart, user) {
  if (user.isPremium && cart.total > 100) return cart.total * 0.2;
  if (cart.total > 200) return cart.total * 0.1;
  return 0;
}

function applyDiscount(cart, discount) {
  return { ...cart, total: cart.total - discount }; // new object, no mutation
}

// ---- Imperative shell: effects ----

async function checkout(cartId, userId) {
  const cart = await db.getCart(cartId);        // effect
  const user = await db.getUser(userId);        // effect
  const discount = calculateDiscount(cart, user); // pure
  const updated = applyDiscount(cart, discount);  // pure
  await db.saveCart(updated);                   // effect
  await email.sendReceipt(user.email, updated); // effect
  return updated;
}

The core is exhaustively testable with plain data. The shell is short enough to verify by reading it. Every decision lives in a function you can test in isolation.

This pattern is the practical answer to “how do I get the benefits of purity in a program that must talk to the world”.

Making functions pure

Most impure functions can be made pure by passing in what they currently reach for.

Pass the dependency instead of reading a global:

// Before
function withTax(price) {
  return price * (1 + taxRate);
}

// After
function withTax(price, rate) {
  return price * (1 + rate);
}

Return a new value instead of mutating:

// Before
function addItem(cart, item) {
  cart.push(item);
  return cart;
}

// After
function addItem(cart, item) {
  return [...cart, item];
}

Pass the time in instead of reading the clock:

// Before
function isExpired(token) {
  return token.expiresAt < Date.now();
}

// After
function isExpired(token, now) {
  return token.expiresAt < now;
}

That last one is a small change with a large payoff: the function becomes trivially testable, including for edge cases like exactly-at-expiry, which are painful to test against a real clock.

Impurity is contagious

This is the property that makes purity hard to maintain: a function that calls an impure function is itself impure.

function processOrder(order) {
  const total = calculateTotal(order); // pure
  logOrder(total);                     // impure
  return total;                        // processOrder is now impure
}

Purity propagates upward. One impure call anywhere in the call tree makes everything above it impure.

This is why the boundary must be drawn deliberately. If you let effects leak into the middle of your logic, the impurity spreads until nothing is testable in isolation.

The discipline is: push effects to the edges, keep the middle pure.

Common sources of impurity

SourceExampleFix
Global stateReading a module-level variablePass as a parameter
Mutationarr.push(), obj.x = 1Return a new value
ClockDate.now(), new Date()Pass the time in
RandomnessMath.random()Pass a seed or the value
I/Ofetch, fs.readFileMove to the shell
Loggingconsole.logMove to the shell
Environmentprocess.envRead once at startup, pass in

The pattern in every fix is the same: take the dependency as a parameter instead of reaching for it.

When purity is not worth it

Purity has costs, and it is not always the right call.

Performance-critical loops. Copying an array on every iteration is O(n) per operation. In a hot loop, in-place mutation is the correct choice. Purity is a default, not a dogma.

Large data structures. Immutable updates to a deeply nested structure can be expensive without structural sharing. Libraries like Immer exist precisely to make this practical.

Simple scripts. A 30-line script that reads a file and prints a result does not need a functional core. The pattern pays off as complexity grows.

UI state that is genuinely local. Not every piece of state needs to be lifted and threaded through pure functions.

The judgement is: use purity where it buys testability and reasoning, and accept impurity where the cost outweighs the benefit.

Practical guidance

  • Default to pure functions for logic, calculations, transformations, and validation.
  • Push effects to the edges — read input at the start, write output at the end.
  • Pass dependencies as parameters rather than reaching for globals.
  • Return new values instead of mutating arguments, unless performance demands otherwise.
  • Test the core exhaustively and the shell by inspection.
  • Do not chase 100% purity — chase a clear boundary between decisions and effects.

For how this fits with broader design principles, see dependency injection without a framework and technical debt conversation. For the testing payoff, why your tests are slow shows how much simpler tests become when there is nothing to mock.

Quotable summary

A pure function returns the same output for the same input and causes no observable side effects. Purity makes code testable without mocks, cacheable, parallelisable, and safe to reorder, because understanding a pure function requires reading only that function. Side effects are necessary — every useful program performs them — so the goal is isolation rather than elimination. The functional core, imperative shell pattern puts all decisions in pure functions and all effects in a thin outer layer, making the core exhaustively testable. Impurity is contagious, since any function calling an impure function becomes impure, so the boundary must be drawn deliberately. Most impure functions can be made pure by passing in what they currently reach for.

Frequently asked questions

What is a pure function in simple terms?
A pure function is one that always returns the same result for the same arguments and does not change anything outside itself. Math functions like Math.max are pure; a function that writes to a database or reads the current time is not.
Why are pure functions easier to test?
Because you only need to call them with inputs and check the output. There is no database to mock, no clock to fake, and no global state to reset, so tests are short, fast, and reliable.
Are side effects bad?
No. A program with no side effects does nothing useful. Side effects are what make software interact with the world. The problem is unmanaged side effects scattered through logic, which makes code hard to test and reason about.
What is the functional core, imperative shell pattern?
It separates a program into a pure core that makes all the decisions and an imperative shell that performs all the effects. The core is easy to test exhaustively; the shell is thin enough to verify by inspection.
Is console.log a side effect?
Yes. It writes to an external stream, which is observable outside the function. A function that logs is technically impure, though logging is usually treated as a benign exception in practice.
Can a function that reads a global variable be pure?
No, unless the global never changes. Reading mutable global state means the same arguments can produce different results depending on when the function is called, which violates the first property of purity.