Comments

What Are Pure Functions?

JavaScript developers are embracing Functional Programming quite a lot these days, and there is a huge advocacy to write Pure Functions. Now, what are Pure Functions? Not long ago, I learned the concept of Pure Functions, and to my surprise, I was already writing many pure functions, without realising that there was a term for it.

Pure Functions

What qualifies as a Pure Function?

A function is considered pure, if it adheres to the following rules:

  1. The function always returns the same output if the same arguments are passed in.
  2. The function does not produce any side-effects.

We have all written pure functions in the past knowingly or unknowingly.
Take a look at a pure function below, that returns a sum of two numbers given two input arguments.

function sumOfNumbers(a, b) {
 return a + b;
}

The output of this function will always remain the same, if the same input arguments are passed in. Simple enough. Pure functions are simple building blocks that have a predictable behavior always. Hence they always return the same predictable output, without any external influence.

Here is a simple example, on what an impure function looks like.


var value = 5;
function impure(arg) {
    return value + 2 + 3;
}

Here the function is considered impure, because it is not using the argument that was passed to it. Instead, it uses an external value which is subject to change. Therefore, making the function impure due to external interference/side-effects.

Alright, let’s talk about the requirement two on side-effects.

What are Side-Effects?

Side effects occur anytime your function interacts with the outside world.

Some examples of common side-effects include:

  • Making an API call
  • Mutating data
  • console logs to the screen
  • Manipulating the DOM
  • Date.now() to get current date/time
  • async await calls/waiting for promises to resolve
  • math.random() to generate random numbers

Well, you may wonder how we can write functions without side-effects all the time. It is quite challenging to avoid side-effects altogether. All I am saying is, for a function to qualify as pure, as the name suggests, it should have no side-effects.

What do I gain by writing Pure Functions?

Pure Functions

Pic courtesy: Picpedia.Org

Alright, we got the definitions out of the way. You may now ask what are it’s benefits.

1. Testing is easy

Imagine, you have a bunch of pure functions, that do only one thing. They don’t have any external side-effects and they always return predictable output. These functions will be so much easier to test, than a function that has a bunch of dependencies and unpredictable behaviour. Writing clean, testable code will help improve your code quality drastically.

2. Debugging code is not a pain

With pure functions, debugging code won’t be a big pain, compared to debugging impure functions. If you run into an issue or bug, and you have narrowed it down to a pure function, then you can be rest assured that you don’t have to look outside the scope of that function to find the issue. Therefore, drastically improving the developer’s debugging experience.

3. Memoization to improve performance

With pure functions, it is guaranteed to return the same output for a given input. This creates possibility of memoization. When the same input is passed on to a function, it can pull the results from a cache, making the app perform faster. Caching can save tons of resources and improve performance. And caching pure functions can be done without any worry, since they are predictable with no side-effects.

4. Maintainable code, easy to refactor

This is an obvious one. With code, that is so clean, easy to test and debug, you end up with very maintainable code as well. This is an important aspect that keeps future in mind. Years/months later if your software has to have additional features, and refactoring, the code that comprises of bunch of pure functions will be extremely intuitive to re-factor. They won’t have any external side-effects that the developer would need to worry about. Even new developers on the team can take up on this task with ease.

A Real-World example that uses Pure Functions

Redux is so popular and most of us have either used it in some projects or have heard of it. Reducers are functions that are part of the Redux pattern and play a crucial role. The most important feature of redux reducers is that, they are Pure Functions.

Reducers are pure functions that take in a state and action and return a new state.

function(state, action) => newState

Reducers are the major portion of the Redux integration and hold a lot of the business logic. And since redux enforces that the reducers have to be pure functions with no side-effects we end up with very elegant and simple functions that are easily maintainable

Redux is a classic example of writing pure functions. It derives inspiration from functional programming and has gained immense popularity in the last few years. It is heavily used in modern web applications for state management. Now you know the reason behind its success, t is it’s requirement to write pure functions. This makes the code testable, clean, easier to debug and maintainable.

Conclusion

We looked into how writing Pure Functions can benefit you and keep your code simple and elegant. Keep in mind that Pure Functions are not limited to JavaScript. This concept can be adopted in any programming language of your choice. It works well with JavaScript and any functional programming language.

If you are looking to improve your JavaScript skills, I highly recommend Mosh’s course on JavaScript.

Checkout all the JavaScript courses here: https://codewithmosh.com/p/full-stack-javascript-developer-bundle

If you enjoyed this post, please do spread the word and share it. Check back again fore more posts.

Adhithi Ravichandran is a Senior Software Engineer based in Kansas City. She is currently working on building mobile apps using React Native for critical healthcare scenarios. Adhithi is a regular conference speaker at various tech conferences. Adhithi graduated with a Masters degree in Computer Science from the University of Kansas and has been in the tech industry for over 7 years. She has worked on several technologies over the years, and one of her recent favorite is React Native.
Tags: ,

One response to “What Are Pure Functions?”

  1. Neshat Ademi says:

    Great Post! Can’t wait for a course React Native…

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts