Pure vs Impure Functions in JavaScript

Understand the Difference Between Pure and Impure Functions in JavaScript

Abdo Amin
Enlear Academy

--

Today, I am going to explain what is “pure” and “impure” in JavaScript.

1- Pure Function:

  • Predictable
  • Has no side-effects

2- Impure Function:

  • Unpredictable
  • Has side-effects

That’s it :)

Thank you for reading……

Just kidding, let me explain few things:

Predictable:

Look at this example and tell me what is the output of calling add function with two arguments x=2, y=2 :

Output is 4. It’s easy to predict, right?

Now, can you predict this one? (👾)

Well….no, you can’t.

Because we can’t “predict” what rand will evaluate to be.

NOTE: let rand = Math.random() * 10 will generate random numbers between 1 to 10.

Side-effects:

Let’s start with an example, can you predict the output? (🤞)

You are right if you predicted 5.

Can you predict what is the output of this function? (🤖)

The output is 4.

This function has side effects…why?

Because it is mutating (changing🤖) a variable outside of the function scope.

Other examples of side-effects:

1- Dom manipulation, because you are “mutating” something outside of the function scope.

2- External dependency, your function depends on something outside of the function scope.

Why can’t we depend on an external source 🤞?

Because we can’t “predict” the input of this source.

What if this source gets mutated🤖? What if the source is random 👾?

Bonus question: What is the type of this function?

A pure function?

Nope, this is an impure function.

Why? because console is an external API not a JavaScript method.

Also, when you make HTTP requests (e.g usingfetch ), you are using an external source, therefore this is an…………..? 👾🤞🤖

Correct, an impure function.

The emojis above indicating that:

An external source🤞might be unpredictable (random) 👾 and might be mutated (changed)🤖.

fetch , promise, and any form of asynchronous functions are impure because JavaScript is synchronous by nature.

In order to introduce asynchronously to JavaScript, also known as AJAX, JavaScript started to depend on external resources such as Web APIs.

Excercise:

What is the type of following functions?

Answers:

1, 4 = impure

2,3 = pure

1- Mutating an outer variable, and depending on an external variable, not an argument passed to it.

4- Mutating an argument (Not sure 100% if this is impure. Let’s discuss it in the comments 🙂)

Recap:

A pure function is always predictable and has no side effects.

An impure function is unpredictable and has side effects.

Side effects include, but not limited to:

1- DOM manipulation

2- Outer scope variable mutation

3- External dependency (APIs, outer variables)

Thanks for reading 😊

--

--

I love React and anything that has JavaScript and frontend in it.