Difference between pure and impure function?

Content taken from this link

Characteristics of Pure Function:

  1. The return value of the pure func­tions solely depends on its arguments
    Hence, if you call the pure func­tions with the same set of argu­ments, you will always get the same return values.

  2. They do not have any side effects like net­work or data­base calls

  3. They do not mod­ify the argu­ments which are passed to them

Char­ac­ter­isitcs of Impure functions

  1. The return value of the impure func­tions does not solely depend on its arguments
    Hence, if you call the impure func­tions with the same set of argu­ments, you might get the dif­fer­ent return values
    For exam­ple, Math.random(), Date.now()

  2. They may have any side effects like net­work or data­base calls

  3. They may mod­ify the argu­ments which are passed to them

function impureFunc(value){
  return Math.random() * value;
}

function pureFunc(value){
  return value * value;
}

var impureOutput = [];
for(var i = 0; i < 5; i++){
   impureOutput.push(impureFunc(5));
}

var pureOutput = [];
for(var i = 0; i < 5; i++){
   pureOutput.push(pureFunc(5));
}

console.log("Impure result: " + impureOutput); // result is inconsistent however input is same. 

console.log("Pure result: " + pureOutput); // result is consistent with same input

Leave a Comment