Pure functions: same input, same output

A pure function has two properties. The same arguments always produce the same result, and the call changes nothing outside the function: no variable of the module, no element of an argument, no file and no screen. (a, b) => a + b is pure, console.log is not, and a function that pushes into its argument is not either.

The idea sounds like a style preference and behaves like an engineering decision. A pure function can be read without knowing the rest of the program, tested with one call and no setup, and cached or run in any order. Most of the higher-order code in the rest of this part is built from pure functions, which is what makes map, filter and reduce so useful.

Same input, same output

The first function below computes from its arguments alone, so two identical calls produce two identical results. The second keeps a counter outside itself and adds to it, so the same call gives a different answer every time. Both are ordinary functions and both are valid programs; only one of them is predictable from the call alone.

function area(width, height) { return width * height; } console.log(area(3, 4)); console.log(area(3, 4)); console.log(area(4, 3)); let total = 0; function addToTotal(value) { total += value; return total; } console.log('first call:', addToTotal(5)); console.log('same call again:', addToTotal(5));

node pure.js

12
12
12
first call: 5
same call again: 10

The three area calls print the same number, and the last two print different ones from the same argument. Nothing is broken in the second function: a running total is exactly what it is for. The point is that its result depends on something the caller cannot see, so the answer to "what does addToTotal(5) return" is a question about the whole history of the program. A function whose result depends on the clock, on a file or on a random number has the same property.

Side effects

The most common side effect in beginner code is a function that changes the array or object it was given. The caller still holds the same object, so the change is visible after the call returns, and the surprise grows with the size of the program. The pure version builds a new value and leaves the argument alone.

function addImpure(list, item) { list.push(item); return list.length; } function addPure(list, item) { return [...list, item]; } const items = ['a']; console.log('impure returns:', addImpure(items, 'b')); console.log('the argument changed:', items.join(',')); const longer = addPure(items, 'c'); console.log('pure returns:', longer.join(',')); console.log('the argument still:', items.join(','));

node side.js

impure returns: 2
the argument changed: a,b
pure returns: a,b,c
the argument still: a,b

The impure call returned a number and changed the argument as a second, invisible result. The pure call returned a new array, and the original kept the two items it had. That second version is what the lesson on copying prepared: the spread copy is shallow, which is enough here because the items are strings. Writing a log line or setting a global are side effects too, and the rule of thumb is that a function should have one job and its side effects should be the job.

Why pure code is easy to test

A test of a pure function is a table of calls and expected values: no setup before the first case, no cleanup between cases, no order that matters. The program below tests one function with three pairs and prints a verdict for each. The counted version at the end shows the opposite: a function with an outside counter needs its state reset between cases, and a test that forgets that is testing the previous case.

function titleCase(text) { return text .split(' ') .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) .join(' '); } const cases = [ ['hello world', 'Hello World'], ['ADA', 'Ada'], ['', ''], ]; for (const [input, expected] of cases) { const actual = titleCase(input); const verdict = actual === expected ? 'ok' : `expected ${expected}`; console.log(JSON.stringify(input), verdict); } let runs = 0; function counted(text) { runs += 1; return titleCase(text); } counted('a'); counted('b'); console.log('runs after two calls:', runs);

node tests.js

"hello world" ok
"ADA" ok
"" ok
runs after two calls: 2

Three cases ran in one loop with nothing between them, and the order could be reversed without a change. The counted function is not wrong, but every test of it has to know that runs starts at zero, and a test suite that runs the file twice sees four. The general shape of the problem is the same with a database, a server or the clock: the test needs a world outside the function before it can begin.

An impure shell around a pure core

Real programs read the clock and print, so the goal is not to remove every side effect but to keep it at the edge. The program below splits the work in two: a pure function that turns text into a number, and a thin function that reads the environment and hands the text over. The impure part touches the environment, and every interesting rule lives in the part that can be tested with a string.

function parseAmount(text) { const digits = text.replace(/[^0-9.]/g, ''); return Math.round(Number(digits) * 100) / 100; } function amountFromEnv() { return process.env.AMOUNT; } process.env.AMOUNT = ' $1,234.5 '; console.log('from the environment:', amountFromEnv().trim()); console.log('parsed:', parseAmount(amountFromEnv())); console.log('parsed again:', parseAmount('99.999'));

node shell.js

from the environment: $1,234.5
parsed: 1234.5
parsed again: 100

parseAmount takes a string and returns a number, so it can be tested with the two strings above and never needs a process environment. amountFromEnv does the impure reading and nothing else. The same split is how a program keeps arithmetic, formatting and validation away from files and sockets, and it is the reason the next lessons can treat functions as values and combine them freely.

Exercises

  1. Give area in pure.js a third argument for a unit and return the text 12 m2. Is the function still pure, and did its output change between two identical calls?
  2. Reset total to 0 between the two addToTotal calls. Which line of the output changes, and what does that say about the state?
  3. Rewrite addImpure so that it returns the new array instead of the length. What has to change in the two lines that print it?
  4. Add a fourth case to the table in tests.js that expects a wrong answer. What does the loop print for it, and does the loop stop?
  5. Move the process.env.AMOUNT assignment above the function declarations in shell.js. Which lines still print the same output, and why does the order not matter for a function that is only called later?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which two properties make a function pure?

    Answer

    The same arguments give the same result, and the call has no side effects

    Determinism and the absence of side effects are the two halves of the definition.

  2. Which of these is a side effect?

    Answer

    Pushing an item into the array that was passed in

    The caller still holds the same object, so the change is visible outside the call, which is what a side effect is.

  3. What does this program print? function f(a) { return a * 2; } console.log(f(2), f(2));

    Answer

    4 4

    The function reads only its argument, so two identical calls give the same value in the same line.

  4. What does this program print? let total = 0; function add(n) { total += n; return total; } console.log(add(1), add(1));

    Answer

    1 2

    The first call moves the outside total to 1 and the second to 2, so the same argument gives different answers.

  5. What does this program print? const list = [1]; function add(list, v) { list.push(v); return list.length; } console.log(add(list, 2), list.length);

    Answer

    2 2

    The push changed the array of the caller, so both readings after the call see two elements.

  6. What does this program print? const list = [1]; function add(list, v) { return [...list, v].length; } console.log(add(list, 2), list.length);

    Answer

    2 1

    The pure version builds a new array, so its length is two while the argument keeps its single element.

  7. Why does a pure function need no setup in a test?

    Answer

    Its result depends only on the arguments of the call

    There is no outside state to prepare, so a call with fixed arguments is the whole test case.

  8. Which function is impure even though it returns a value?

    Answer

    One that reads a counter of the module and adds to it

    It both reads and writes state outside itself, so its result depends on the history of the program.

  9. What is the point of an impure shell around a pure core?

    Answer

    The side effects stay at the edge and the rules stay testable

    Reading a file or a clock has to happen somewhere, and keeping it in a thin layer leaves the logic callable with plain values.

  10. What does this program print? function f(a) { return a.map((n) => n + 1); } const values = [1, 2]; console.log(f(values).join(","), values.join(","));

    Answer

    2,3 1,2

    map builds a new array, so the returned values changed and the argument kept its own.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev