Introduction

“Pure function” is one of those terms that might be intimidating at first, but the concept is actually quite simple. In this post, I’ll quickly define what pure functions are and why they’re good.

Two Criteria

To be considered pure, a function must meet two criteria: it must have (1) identical output for identical inputs and (2) no side effects.

Let’s dig deeper into each of these criteria.

Identical output for identical inputs

Let’s first consider a function that doesn’t have identical output for identical inputs: the greet function below:

let greeting = 'Hello';

function greet(name) {
  return greeting + ' ' + name;
}

console.log(greet('Paul'));
// Hello Paul

We see here that the output of the greet function can change even if the input name to that function stays the same (all we have to do is change the greeting variable value).

How can we make the output identical for identical inputs? It’s as easy as just ensuring the greeting is also an argument for the function:

function greet(greeting, name) {
  return greeting + ' ' + name;
}

console.log(greet('Howdy', 'Paul'));
// Howdy Paul

Now, there’s nothing we can do to make the greet function return a different result unless we change one of its input arguments.

No side effects

A side effect is when the function changes something outside the scope of the function. Again, let’s take a look at an example of a function that violates the “no side effect” rule:

const user = {
  username: "bob1234";
}

let isValid = false;

function validate(user) {
  if (user.username.length > 4) {
    isValid = true;
  }
}

We can see that we’re clearly changing the isValid variable, which is outside the scope of the validate function. (Note: if your function doesn’t return anything, that’s a strong indication that it might have side effects!).

#function

What is a Pure Function?
5.45 GEEK