Pure and Impure Functions in Javascript

Reading Time: 2 minutes

Introduction

Hello readers! In this blog, we will be going through the concept of pure and impure functions in javascript and their advantages. So let’s dive into it.

Pure Functions

Pure functions are those functions that do not create any side effects. In simpler terms, you will not be changing any external code in a pure function and the output for that function will always be the same for the same input. 

To get a better understanding of it, let us see an example:

function add(num1, num2) {
	return num1 + num2;
}

This is a simple add function that will make the sum of two numbers. So we can see that this function is not changing any external code and the output for this function is predictable.

Advantages of Pure Functions

  • Pure functions are independent as they do not change any external state.
  • They are easier to read and debug.
  • You can clone an external state into a pure function.

Here are some examples of side effects that a function should not include in order to be a Pure Function:

  • Making an HTTP call
  • Using Math.random()
  • Mutating data
  • DOM Manipulation
  • Printing console statements (console is an external API, not a Javascript method)

Impure Functions

Impure functions are those functions that will create some side effects. An impure function will change some code outside of its scope. Let us see this example:

function add(num1) {
	return num1 + Math.random();
}

Now the output of this function is not predictable so this will be considered an impure function.

To understand side effects, check this example:

let sum = 0;
function add(num1, num2) {
	let result =  num1 + num2;
	sum = result;
	return result;
}

In this case, we have assigned the value of the result to the sum which is outside the function scope. So this function is having a side effect.

Conclusion

So now we understand what is pure and impure functions in Javascript and as a best practice, we should always try to use pure functions as they will not create any side effects. To learn more about other function concepts in Javascript follow this link.

For more updates, please follow our LinkedIn page- FrontEnd Studio.

Thank you for sticking to the end. If you like the blog, please don’t forget to give a thumbs up and share it. Feel free to share your thoughts about this blog in the comments.

Written by 

Kiran Jeet Kaur is working as a Software Consultant in Knoldus. Her practice area is Front End. She is always open to learn new things. Her hobbies include watching movies and listening to music.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading