Be the first user to complete this post

  • 0
Add to List

Pure vs Impure functions

Characterestics of Pure Functions

  • The return value of the pure functions solely depends on its arguments
    • Hence, if you call the pure functions with the same set of arguments, you will always get the same return values
  • They do not have any side effects like network or database calls
  • They do not modify the arguments which are passed to them
For example,
function calculateSquareArea(x) {
   return x * x;
}

Characterisitcs of Impure functions

  • The return value of the impure functions does not solely depend on its arguments
    • Hence, if you call the impure functions with the same set of arguments, you might get the different return values
    • For example, Math.random(), Date.now()
  • They may have any side effects like network or database calls
  • They may modify the arguments which are passed to them
For example,

function squareAll(items) {

  var len = items.length;
  for (var i = 0; i < len; i++) {
    items[i] = items[i] * items[i];
  }

  return items;
}



Also Read:

  1. Array filterUntil function implementation for javascript
  2. Testing promise sequence using mocha, chai, chai-as-promised, sinon
  3. css - align text to an image vertically
  4. Execution sequence of a React component's lifecycle methods
  5. Passing the store down implicitly via context in a react redux app