• JavaScript

What Is a Pure Function in JavaScript?

by Yazeed Bzadough

added on October 18, 2022 (2y ago)

The Checklist

A function must pass two tests to be considered “pure”:

  1. Same inputs always return same outputs
  2. No side-effects

Let’s zoom in on each one.

1. Same Input => Same Output

Compare this:

const add = (x, y) => x + y;
 
add(2, 4); // 6

To this:

let x = 2;
 
const add = (y) => {
  x += y;
};
 
add(4); // x === 6 (the first time)

Pure Functions = Consistent Results

The first example returns a value based on the given parameters, regardless of where/when you call it.

If you pass 2 and 4, you’ll always get 6.

Nothing else affects the output.

Impure Functions = Inconsistent Results

The second example returns nothing. It relies on shared state to do its job by incrementing a variable outside of its own scope.

This pattern is a developer’s nightmare fuel.

Shared state introduces a time dependency. You get different results depending on when you called the function. The first time results in 6, next time is 10 and so on.

Which Version’s Easier to Reason About?

Which one’s less likely to breed bugs that happen only under certain conditions?

Which one’s more likely to succeed in a multi-threaded environment where time dependencies can break the system?

Definitely the first one.

2. No Side-Effects