DEV Community

Cover image for What is Purity in Javascript and Why Does It Matter?
Lucas Rodriguez
Lucas Rodriguez

Posted on • Originally published at Medium

What is Purity in Javascript and Why Does It Matter?

The process of studying JavaScript usually begins in a very practical way. From declaring variables to understanding the hell of Asynchronous JavaScript, the more theoretical concepts get left out. And this gap starts to get annoying when you get into deeper topics.

With this in mind, let's start by explaining some of the more theoretical (and even philosophical) concepts of Modern JavaScript, starting with purity. 👇

What is this purity?

Imagine that you are creating a complex system using the functional programming paradigm. This means that your project will have a plethora of functions, one calling the other, to the point where there comes a point where the code takes on a life of its own and does things you didn’t ask for.

If your goal is not to create a crazy AI, this is something you want to avoid at first. You don’t want that by changing something in one function, something in another function that you don’t even know where it is will do a carpentered double twist with no idea how it was done.

A pure function, therefore, is one in which there is no change. An impure function is one that modifies variables, states, or data beyond its scope.

The philosopher Heraclitus said that it is not possible to bathe in the same river twice, because the river of a second ago is no longer the same river of now, due to its flow. Pure functions go in the opposite direction and try to preserve the same river so that you can bathe in it as many times as you want, always knowing what will happen.

Pure functions

Let’s take a look at this JavaScript function:

const calculateDouble = (num) => num * 2;
Enter fullscreen mode Exit fullscreen mode

Here we have a function that will calculate the double of a number. If we call calculateDouble(4) we get the result 8. No matter how many times we call this function, we know that if the argument is 4, the result will be 8. If the argument is 5, the result will be 10, and so on.

calculateDouble(4) // returns 8
calculateDouble(4) // returns 8
calculateDouble(4) // returns 8
// the result never changes
Enter fullscreen mode Exit fullscreen mode

A pure function is going to have this unchanging behavior. It’s a function that knows who it is. It’s like that senior person at work, super disciplined and methodical. Everyone in the firm knows what time she is going to have a cup of coffee, how she is going to respond when approached, and so on.

There are two characteristics:

  1. Given the same input, it will always return the same output.

  2. It will not produce any side effects.

Impure functions

Now look at this function and try to understand what it is doing:

let num = 8;
const calculateDouble = () => num *= 2;
Enter fullscreen mode Exit fullscreen mode

This function has the same purpose as the previous example. But notice that it is accessing a variable outside its own scope. When we call it with calculateDouble()we will get the result 16. If we call it again, the result will be 32, and so on. We have here an impure function.

calculateDouble() // returns 16
calculateDouble() // returns 32
calculateDouble() // returns 64
Enter fullscreen mode Exit fullscreen mode

Another example of an impure function is:

const showAlert = () => {
  alert('This is a side effect!');
}
Enter fullscreen mode Exit fullscreen mode

This is also an impure function because it has a side effect. The result will always be the same depending on the environment you have configured, i.e., it will always return an alert in the window with the same message. However, for it to produce this alert the DOM API is accessed. In the case of the DOM we are assured that it will probably never change, but if it were another API, who would guarantee us immutability?

Another example of an impure function is the following:

const multiplyRandom = (num) => num * Math.random();
Enter fullscreen mode Exit fullscreen mode

Here we are taking a number and multiplying it by a random value (which is what the function Math.random() does. Incidentally, it is also impure). Even if your arguments are always the same, the results will be different:

multiplyRandom(3) // returns 1.2427312565643085
multiplyRandom(3) // returns 0.0966362658711748
multiplyRandom(3) // returns 2.493662851387264
Enter fullscreen mode Exit fullscreen mode

It is clear from these examples that the impure function doesn’t really know what it returns. Compared to that stable co-worker, this is the one who comes in at 8 a.m. one day and is almost 12 p.m. the next, and you don’t know whether to respond politely or angrily. But it could be that this is exactly the creative employee who does something amazing if he has a leader capable of using his talent.

*So don’t condemn the impure functions. *Avoidance is always good, but they can be important if you know where to use them, taking great care to document the behavior so that the code is understandable to others or even to you in the future.

What are the benefits of using pure functions?

  • Reproducibility: one of the principles of a scientific experiment is its ability to be reproduced and the result remain the same. In programming, this ability allows tests to be run more easily, bugs to not occur…

  • Parallelization: although JavaScript, in theory, runs with single thread, i.e. one thing at a time, asynchronous functions are already quite common. With pure functions, you can call them in parallel without fear of the result changing, saving execution time.

  • Memoization: this term means, in this case, the ability to store in memory the result of the function. We saw that the result of the function will always be the same. This means that we can save the value of the function in a variable and then use it instead of the function and the result will be the same.

There are many other benefits, especially when you use functional programming, but for this we need to go into other concepts that will be the subject of future posts.

Conclusion

If you have any questions or want to share any tips, please leave a comment below. I would love to read your opinion and feedback!

Thanks for reading! Follow me in this platform to read more programming content. Have a great day, see you soon! 👋

Latest comments (0)