Difference between pure and impure functions.

Difference between pure and impure functions.
5 (100%) 2 votes

  1 minute

What are pure and impure functions?

Pure functions:

These are functions which are sure to provide exact result when the same arguments are passed. For having a function as pure function if must not have any external variable, data store call, ajax request or any other global variables.

This means that you can be completely sure that every time you call the function with the same arguments, you will always get the same result.

Example:

function square(x){
     return x*x
}

The above function is pure function as we are always certain what will be result and there will be no different results for same input.

 

 

Difference between pure and impure functions.
Taken from https://image.slidesharecdn.com/functions-120306014735-phpapp01/95/functions-in-java-6-728.jpg?cb=1330998699

Impure Functions:

When function uses any variables not passed in as arguments, the variables used inside functions may cause side effects. Lets say in case of ajax calls it will fail, In such cases the function is called impure function. When a function depends on variables or functions outside of its lexical scope, you can never be sure that the function will behave the same every time it’s called. Following are impure functions:

function getRandom(number) {
  a = Math.random()
  if(a > 10){
     return a
  }
  else{
     return 10
  }
}

Here the function getRandom is impure as it is not sure what will be the result when we call the function.

So this is the difference between pure and impure functions.

Liked the article please share and subscribe.


Gaurav Yadav

Gaurav is a Full Stack Web Developer and Blogger. Sportsperson by heart and loves football. He has experience with various frameworks in php, python and javascript. Loves to explore new frameworks and evolve with the trending technology.

1 COMMENT
  • Rahul sinha
    Reply

    And Pure function also it does not change the passed arguments instead it makes the copy of the arguments and then makes the changes .

Leave a Reply

Your email address will not be published. Required fields are marked *