Contents

Functional programming in Javascript - Pure functions

What are pure functions?

Here we are going to talk about another fundamental concept of functional programming, pure functions.

First of all let’s try defining what pure functions are.

A pure function is a function that is deterministic and has no side effects.

Now, let’s see what this actually means.

What is a deterministic function?

The word deterministic may sound intimidating but it should not because in the end all boils down to the concept that given the same input, the function will always return the same output.

A simple example

Here we have a function that takes 2 numbers as arguments and returns the sum of them.

1
2
3
4
const sum = (x, y) => x + y;

console.log(sum(2, 2)) // 4
console.log(sum(2, 2)) // 4

As you can se it doesn’t matter how many times the function is called, it always returns the same output.

Let’s now see an example of non-deterministic function.

Consider the following example
1
2
3
4
5
6
let x = 2;

const addToX = (y) => x += y;

console.log(addToX(2)); // 4
console.log(addToX(2)); // 6

As you can see every time addToX is called x gets re-assigned yielding different results.

This not only makes the function non-deterministic but it also introduces side effects.

Pure functions produce no side effects

First of all we should clarify what side effects are.

What is a side effect?

A side effect is any change that can be observed outside the called function.

In other words what happens inside a function must be invisible from the outside wold. The only way for a pure function to share the result of its work is by returning a value.

Here is a list of the most typical side effects:

  • Modifying external/global variables
  • Mutating the parameters that are passed as arguments
  • Using console.log()
  • Changing the file system (i.e. writing to files)
  • Performing HTTP calls
  • etc…
Note

It’s important to understand that not all side effects are pure evil.

All programs will produce some sort of side effect such as calling APIs or printing to some stdout.

The goal here is to minimize the side effects, so our program is easier to understand and test.

How to avoid side effects

The most dangerous side effects are the ones that mutate variables outside the scope of the function.

Pure functions can avoid this by only using local state.

In other words the only dependencies they can be accessed should be the parameters that are passed as arguments which must not be mutated to respect the principle of immutability.