Pure functions

Pure functions

What is a pure function?

You can say about a function that is pure when for the same arguments it returns the same result every time.

Examples:

  1. Pure

The function that we will describe below will return the same result for any given 2 numbers.

function multiply(a, b) {
  return a * b;
}
  1. Impure

Impure function means that we will not get the same result every time we invoke with the same parameters and that is because we are referring to another variable that is living outside of our function and that one can be changed before our function get’s executed and thus changing our result.

const c = 10;
function multiply(a, b) {
  return a * b * c;
}

Using pure functions will make your code much more readable, easy to understand and easy to test.

Related Posts