Skip to main content

Pure Function (Computer Science)

A function is considered a Pure Function if

  1. for identical arguments, it produces identical return values
  2. it is side effect free

In this context, a Pure Function is similiar to a mathematical function.

Referential Transparency

If a function is pure, it is referential transparent


Pure Function

The following function ff

f ⁣:RR,xxxf\colon\R \rightarrow \R, x \mapsto x*x

translates to JavaScript

    const f = x => x * x;

The function conforms to the definition of a Pure Function:

  1. for each input xx it always returns xxx*x.
  2. It is side effect free (i.e. it does not change the state of any other variable)

Impure Function

Whereas the following functions are considered impure:

    function f (x) {
return this.x * x;

The method violates 1. of the above definition for a Pure Function: It produces variants because of the non-local-variable this.x. The state of this.x is unclear to f, the result is nondeterministic.

    function f (x) {
this.x = x;

The method violates 2. of the above definition for a Pure Function: Although it always produces undefined for the given input x, it is not side effect free since it changes the non-local variable this.x.

see also