← Back to JavaScript, page 9

javascript-0173 · Easy fresher

What is a pure function, what counts as a side effect, and why do interviewers care?

A pure function always returns the same result for the same arguments and changes nothing outside itself. Side effects include mutating inputs or globals, reading time or randomness, logging, network calls, and touching the DOM. Pure functions are easy to test, cache, and reason about, so apps keep them at the center and push side effects to the edges.

Full answer

A function is pure when two conditions hold. First, the same input always gives the same output (it does not depend on hidden state such as a global variable, Date.now(), or Math.random()). Second, it causes no side effects: it does not change its arguments, global variables, the DOM, files, or the network, and it does not print anything.

Common impure things that surprise beginners:

  • array.sort(), reverse(), push(), and splice() mutate the array they are called on. Calling them on a parameter makes your function impure. Use toSorted, toReversed, slice, or spread to work on a copy.
  • Mutating an object parameter: user.active = true changes the caller's data.
  • Reading a variable from an outer scope that can change.
  • console.log is a side effect, even though it is usually harmless.
  • Returning a different result for the same input because of time or randomness.

Why it matters: pure functions are easy to unit test (no setup, no mocks), safe to cache with memoization, safe to run in any order or in parallel, and easy to debug because the output depends only on the input. Libraries such as Redux reducers and React render functions assume purity, and bugs appear when they are impure.

Programs still need side effects, because otherwise nothing would be displayed or saved. The usual design is a pure core with a thin impure shell: compute the new state with pure functions, then apply it to the screen or the server in one place. To keep a function pure while it needs time or randomness, pass them in as arguments, for example createId(random) or isExpired(date, now).

Interview tip: Object.freeze helps to detect mutation but is shallow, and purity is a design rule, not something the language checks.

javascript
'use strict';
let taxRate = 0.2;

const impureTotal = (price) => price * (1 + taxRate);
const pureTotal = (price, rate) => price * (1 + rate);

function impureSortNames(names) {
  return names.sort();
}
function pureSortNames(names) {
  return [...names].sort();
}

function impureActivate(user) {
  user.active = true;
  return user;
}
function pureActivate(user) {
  return { ...user, active: true };
}

console.log(impureTotal(100));
taxRate = 0.5;
console.log(impureTotal(100), 'same input, different output');
console.log(pureTotal(100, 0.2), pureTotal(100, 0.2));

const names = ['Maya', 'Ben', 'Asha'];
const sortedCopy = pureSortNames(names);
console.log(sortedCopy, names);
const sortedInPlace = impureSortNames(names);
console.log(sortedInPlace === names, names);

const user = Object.freeze({ id: 1, active: false });
console.log(pureActivate(user), user);
try {
  impureActivate(user);
} catch (error) {
  console.log('frozen input exposes the mutation:', error.name);
}

const isExpired = (expiresAt, now) => now >= expiresAt;
console.log(isExpired(1000, 999), isExpired(1000, 1000));

const createId = (random) => 'id-' + Math.floor(random * 1000);
console.log(createId(0.123), createId(0.123));

const pureSteps = [1, 2, 3, 4].filter((n) => n % 2 === 0).map((n) => n * 10);
console.log(pureSteps);

Run with Node.js v24.22.1 as js-173.js; two runs gave identical output. Output: 120 150 same input, different output 120 120 [ 'Asha', 'Ben', 'Maya' ] [ 'Maya', 'Ben', 'Asha' ] true [ 'Asha', 'Ben', 'Maya' ] { id: 1, active: true } { id: 1, active: false } frozen input exposes the mutation: TypeError false true id-123 id-123 [ 20, 40 ]

Key points

  • Pure: same input, same output, and no effect outside the function.
  • Side effects: mutating inputs or globals, time, randomness, I/O, logging, and the DOM.
  • Copy before using sort, reverse, push, and splice on parameters.
  • Pure code is easier to test, memoize, and run in parallel.
  • Use a pure core and an impure shell; pass time and randomness in as arguments.

Common mistakes

  • Calling sort or reverse on a parameter and thinking that no data changes.
  • Using Date.now or Math.random inside a function that should be pure.
  • Thinking Object.freeze makes nested objects immutable.
  • Believing that all side effects are bad, instead of controlling where they happen.

Follow-ups

  • Why must a Redux reducer be pure?
  • How do you test code that uses the current time?
  • Is a function that logs to the console pure?

Tips

  • Give the two-part definition and an example of each part.
  • Show a sort on a parameter as the typical hidden mutation.
  • End with the pure core and impure shell idea.