What is Pure functions and Impure functions in javascript?

What is Pure functions and Impure functions in javascript?

Last updated:4/3/2021 7:15:48 AM

1 Answers

Shrikant Mishra
Shrikant Mishra

Pure functions Vs. Impure functions

Pure functions

The pure functions always return the same result when the same arguments are passed in. And, this function does not underlet on any state, or data, change during a program's execution. That is must only depend on its input arguments. So, This function does not have any side-effects like network or database calls and does not modify the arguments which are passed to them.

example

function getSquare(x) {

   return x * x;
}

Impure functions

Whereas the Impurefunctions can change the internal state of one of its arguments or the value of some external variable. It can have any side-effects such as networks or database calls and it can modify the arguments that have been passed to them.

example

function getSquare(items) {

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

 Math.random() is an impure function; it can changes the internal state of the Math object so you get different values on successive calls.

Answer