Go to Home

Pure Functions in Javascript

In 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.

pure-functions

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

  1. No random values
  2. No current date/time
  3. No global state
  4. 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

  1. Self documenting- Everything a function needs are clearly mentioned and there is no dependency outside of it
  2. Easier testing - Since there is zero dependency, it is easier to test
  3. Concurrency - Because there is no need of any global state, we can run these functions parallels without any side effects
  4. 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!

One email per week. No spam ever.

Subscribe