Difference between pure and impure functions.

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.


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
     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 cloud infrastructure engineer and a full stack web developer and blogger. Sportsperson by heart and loves football. Scale is something he loves to work for and always keen to learn new tech. Experienced with CI/CD, distributed cloud infrastructure, build systems and lot of SRE Stuff.

  • Rahul sinha

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

  • Best practices for programming - Learn Steps

    […] Try to write pure functions instead of impure functions. Read here about pure and impure functions […]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.