DEV Community

Chanchal Verma
Chanchal Verma

Posted on

What are Pure and Impure functions in JavaScript

Once upon a time, in a small village, there was a mathematician named John who loved solving mathematical problems. John used to teach math to kids in his village. One day, John was explaining about functions to his students, he told them that a function is a set of instructions that can be reused multiple times.

John explained to his students that there are two types of functions in JavaScript, Pure functions and Impure functions.

He said that Pure functions are the ones that always return the same output for the same input, no matter when or where they are called. Pure functions do not have any side effects, which means they do not modify any variables outside of their scope, and they also do not interact with the outside world in any way.

On the other hand, Impure functions are the ones that do not always return the same output for the same input, and they may modify variables outside of their scope or interact with the outside world in some way.

To explain it to his students, John took an example of a pure and an impure function.

`

Image description

You can more deep dive into it in the following way :

In simple terms, pure functions do not have an internal state. Therefore, all operations performed in pure functions are not affected by their state. As a result, the same input parameters will give the same deterministic output regardless of how many times you run the function.To get a better understanding, let’s consider the following example.

`function add(a,b) {
return a + b
}
console.log(add(4,5))

`

This example contains a simple add() function, which gives 9 as the output. It is a very predictable output, and it does not depend on any external code. This makes the add() function a pure function.
If a function is declared pure and does not have a state, it can share many instances inside a class. Also, it is advised to avoid mutations inside pure functions.
Advantages of pure functions

  • A pure function works as an independent function that gives the same output for the same inputs.
  • Pure functions are readable because of independent behavior. Moreover, they are straightforward to debug.
  • You can clone an external state into a pure function, but it does not change the purity of the function.

Impure Functions
An impure function is a function that contains one or more side effects. It mutates data outside of its lexical scope and does not predictably produce the same output for the same input.
For example, consider the following code snippet:

`var addNew = 0;
function add(a,b){
addNew =1; return a + b + addNew}
console.log(add(4,5))

`

In the above example, there is a variable named addNew, and it is declared outside of the add() function. But the state of that variable is changed inside the add() function. So, the add() function has a side effect on a variable outside of its scope and is therefore considered an impure function.
JavaScript doesn’t adhere to rigorous notions of function purity and immutability. Any program you develop will need impure functions to modify the state of JavaScript variables (named memory locations).
In general, it’s ideal to keep the impure elements of your programs distinct from the data processing, which is usually pure. Also, updating and maintaining your applications will be much easier if you confine impure elements to their particular functions.

Example of impure functions :
Math.random(), Date.now(), arr.splice(), arr.push(), arr.sort()

Advantages of impure functions

  • Impure functions can use an in-place solution to reduce the space complexity.
  • In impure functions, the state can be modified to use the parent variable and call for the function compiling.
  • As mentioned, the main difference between pure and impure functions in JavaScript is side effects. So, let’s discuss some specifics about the side effects.

Pure functions vs. impure functions

Let’s compare and contrast the differences between pure and impure functions:

  • Pure functions do not have side effects. Impure functions can cause side effects.
  • Pure functions return the same output if we use the same input parameters. However, impure functions give different outcomes when we pass the same arguments multiple times.
  • Pure functions always return some results. Impure functions can execute without producing anything.
  • Debugging pure functions is relatively easier than debugging impure functions.
  • Pure functions cannot execute AJAX calls or standard DOM manipulation.
  • Impure functions aren’t inherently wrong. They merely can cause some confusion in more extensive systems in the form of spaghetti code .

For suh more Cding content you can follow me on
Github
LinkedIn
DEV

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Writing a strictly pure function in JS is actually more difficult than you might think. Due to the way that the language works, your simple add function can actually be made to behave in an impure manner - returning different results for the same inputs.

const val1 = { valueOf: ()=>Date.now() }
const val2 = 1

function add(a, b) {
  return a + b
}

// Same inputs, different results!!
console.log(add(val1, val2))  // 1682750612464
console.log(add(val1, val2))  // 1682750613915 
Enter fullscreen mode Exit fullscreen mode

This is possible because of coercion. At the point when the object val1 is passed into the function, it is always the same object... hence, the inputs to the add function in both console.log statements are the same. However, during the addition, JS coerces the object to a number - which in this case will be the value from the valueOf method.

Isn't JS fun? 😛

Collapse
 
zelenya profile image
Zelenya • Edited

👋 Nice post! You might want to double-check your formatting; it looks like code snippets didn't come out as you probably intended (multiline code requires triple quotes instead of one. Here's a formatting guide in case you need some help troubleshooting. Best of luck!

Collapse
 
chanchals7 profile image
Chanchal Verma

Thank you Zelenya for suggestions.