Pure Functions in Javascript
Jul 09, 2020In continuation with my last article I wrote about Currying technique, today I'm going to explain you what are Pure functions in Javascript.
We say a function is pure if every time we call it with the same arguments, it always returns the same result.
For example, check the following function, do you think it is pure?
It is not. Every time we give same argument, it is going to give us different result each time. Now, check the next example
Here, how many times ever you give same argument, it is going to give us the same result.
Pure Functions
In order, to create a pure function, you should not use the following ones
- No random values
- No current date/time
- No global state
- No mutation of parameters
Now, let's see another real world scenario. Assume that you wanted to build a function which checks if the user is major or minor
At first you might think this is pure function, because anytime you send 18 as its argument, it'll return true every time. But it is not. You can clearly see our eligibility function depends on minAge global variable. Hence, the above function is impure and the result will change the moment you modify the minAge.
So, lets make it pure function
Now, irrespective of how many times you call this function, it'll always return the same result.
Benefits of Pure Functions
- Self documenting- Everything a function needs are clearly mentioned and there is no dependency outside of it
- Easier testing - Since there is zero dependency, it is easier to test
- Concurrency - Because there is no need of any global state, we can run these functions parallels without any side effects
- Cacheable - As we know the result would always be same, we can cache the result, instead of performing it again and again
Now that we know what are pure functions, can we now implement the above example using the Currying technique which I explained in my previous article and simplify the code?
Perfect! We have successfully reduced passing the minAge parameter again and again using Currying technique and made our function oneliner. Pretty sweet!
See you in another article! Happy Coding!