Pure Functions and Side Effects

what is a pure function

What is a pure function? It is a function that returns the same output for the same inputs and does nothing observable besides returning that value. Reading hidden state or changing something outside itself makes it impure.

This essay in our programming essays collection stays narrow. It defines purity, pairs pure and impure behaviour, and ends with a practical way to split real code into testable logic and a thin layer of effects.

The conditions that define purity

A pure function meets two conditions together. GeeksforGeeks describes it as a function that always returns the same output for the same input parameters, and that depends only on those parameters. Meeting one condition without the other is not enough, and most real-world impurity comes from breaking one of them quietly.

Same input, same output

Call a pure function repeatedly with the same argument and the result never changes. Adabeat’s functional programming guide puts it this way: provide the same input multiple times and it will consistently produce the same output. Determinism is the name for this property, and it is what lets you reason about a call without knowing when or how often it runs.

The standard clean example is a string helper. GeeksforGeeks shows a capitalize function that returns a new uppercase string, and because it does not modify any state or have side effects, it counts as pure. The caller’s original string is untouched and the only product of the call is the returned value.

Dependence on inputs only

The second condition is about what a function is allowed to look at. If the result can be worked out from the parameters alone, nothing hidden can change it between calls. Anything else the body reads, such as a global value, is a hidden input, and hidden inputs are where determinism usually breaks. When you review a function for purity, scan the body for every name that is not a parameter or a constant.

Pure and impure side by side

The table lines up the two kinds of function on the criteria that matter in daily code. Treat it as a checklist: a function that lands in the right-hand column on any row is impure.

Criterion Pure function Impure function
Output for the same input Always the same Can differ between calls
What it depends on Only its input parameters Can depend on other values, such as the current date produced by new Date()
Effect on state Does not modify state Can modify the state of the application or have side effects
Testing Easier to test Harder to test

The comparison follows GeeksforGeeks’ pure versus impure breakdown, with the date example from a dev.to essay on writing pure functions.

What counts as a side effect

A side effect is, in the words of that same dev.to essay, any observable effect besides returning a value to the invoker. The test is whether something outside the function can tell that it ran, other than by receiving its return value. Common kinds fall into a few groups.

Each cout line writes a prompt to the console. That output reaches the user without passing through a return value, which is what makes it a side effect.
  • Console output and logging. Calling console.log to output some information makes a function impure, because the output is observable and is not part of the return value.
  • File, database and network access. Adabeat lists functions that read from or write to external files, databases, or network resources as impure. Reads count as well as writes, since the result then depends on something outside the parameters.
  • Global state. Altering global variables can have wide-reaching consequences across your codebase, according to Adabeat. GeeksforGeeks gives a small case: a function that bumps a global counter reports 1 on one call and 2 on the next, so identical calls produce different results.

Impure functions are not defective by nature. GeeksforGeeks simply defines them as functions that can modify the state of the application or have side effects. The practical question is where you allow them, not whether they exist.

Referential transparency

Referential transparency is the formal property behind the everyday idea that a pure call can be swapped for its result. A McMaster University reference page states that each expression denotes a single value which cannot be changed by evaluating the expression. It adds that the value of an expression depends only on the values of its constituent expressions, and that evaluation simply changes the form of an expression but never its value.

In programming terms, you can replace a function call with its result without changing the behaviour of your program, as Adabeat explains. That substitution is a useful mental test. If you can mentally paste the returned value where the call stood and the program means the same thing, the call is behaving transparently. If pasting the value would lose something, such as a log line, a written file or a changed counter, the function has an effect that the value does not carry.

Immutability and pure functions

Immutability in programming means that data is not changed once created. Instead of altering a value, code builds a new one. It matters here because modifying an argument is a state change, and a function that does so is no longer pure.

Code that fills a dictionary and then returns it. When you read code like this, check whether the dictionary was passed in by the caller or created inside the function.

Adabeat illustrates the difference with an array example. The addElementImmutably function returns a new array instead of modifying the original one, and the original array remains unchanged. A version that pushed onto the caller’s array would produce the same visible result for a single call, but the caller’s data would silently differ afterwards.

The habit is simple to apply. Treat every parameter as read-only, return new values, and a whole class of side effects disappears without any special tooling.

Why pure functions are easier to unit test

Pure functions are easier to test because they have predictable behaviour, according to GeeksforGeeks. A unit test for one needs only arguments and an expected return value. There is no environment to prepare beforehand and nothing to inspect afterwards.

The contrast shows up with hidden inputs. The dev.to essay describes a function that uses an impure value produced by new Date() to work out a difference from the current day. Any test written for it would be very brittle, because the expected answer changes as the clock moves. A simple swap to require a date string for computing the difference makes it a pure function, and the test can then supply whatever date it likes.

A colour-conversion routine in PHP. A string goes in and computed values come out, the input-to-output shape that pure functions share.

The same essay tests a pure function called expectedReqBody directly. Because that function only transforms its inputs, the test needs no mocks. That is the practical payoff of the earlier conditions: if a function depends only on parameters and returns a value, a plain assertion is enough to check it.

A green checkmarked test results panel sits beside the test file, and a small orange plush toy rests on the desk at right.

Separating pure logic from side effects

Real programs cannot be purely functional in every layer, so the useful skill is arranging code so that decisions are pure and effects are small. The dev.to essay recommends extracting pure functionality into reusable and testable functions. Work through existing code in this order.

  1. Spot the hidden inputs. Look for anything the function reads that is not a parameter, such as the current date or a global value.
  2. Pass them in as arguments. Supplying a date string instead of reading the clock is the example that turns the date function pure.
  3. Extract the decision-making. Move calculations and transformations into functions that only take values and return values.
  4. Keep effects in thin wrappers. Let a small function do the printing, writing or network call, and have it call the pure functions for the actual work.
  5. Test the pure part directly. Use plain assertions on the extracted functions, and keep any tests of the effectful wrapper few and simple.

This split is also a compact way to approach how to teach programming how to teach programming, since each rule can be checked by calling a function and watching what happens. Once functions and state feel familiar, an essay on a different kind of shared state asks how does git merge work.

Frequently asked questions

Is a function that returns a random number pure?

No. GeeksforGeeks gives a getRandomNumber function that generates a new random number each time it is called, so the same call can return different values and the function is impure.

Can a whole application be written with pure functions only?

Not in practice. The dev.to essay points out that we can’t really build an app that does anything of note without side effects. Pure functions handle the logic, and effects sit around them.

Why does a side effect break referential transparency?

The McMaster University reference page explains that in an imperative routine the side effect prevents the substitution of the expression’s value. Replacing the call with its result would drop the effect, so the program would no longer mean the same thing.

Why does purity matter in React?

ExplainThis notes that impure functions can cause unstable renderings and unexpected UI presentations. A pure function, with the same input giving the same output and no side effects, keeps what is drawn predictable. See its React pure function explanation.