Website logo

08 May 2018

Understanding
Pure
Function

Pure function is a function which you give the same arguments it will return the same output. It's simple, predictable, and easy to test than impure function. You cannot rely on outer scope variable to do calculation inside a pure function. Rely on it's arguments and inner scope instead.

This is an example of pure function :

function sum(a, b) {
  return a + b;
}

sum(1, 2); // It always return 3 (1 + 2 = 3)
sum(5, 1); // It always return 6 (5 + 1 = 6)

So the criteria of pure function is :

  1. Given the same arguments and then return the same output.
  2. No side effects.

Side effects are like :

  1. Mutates and rely on outer scope variable to do calculation
  2. Doing network request
  3. Print to console
  4. DOM manipulation

If don't meet the criteria, it's certainly an impure function. Impure function is not predictable, you can't expect what the return value is. If you call impure function inside a function, that's function will be impure.

This is an example of impure function :

// So you know what the return value is ?
Math.random();

let i = 0;

// It mutates and rely on outer scope variable to do calculation
function add(a) {
  i += 2;
  return i + a;
}

// Same argument but return different value
add(2); // it returns 4 (i = 2)
add(2); // it returns 6 (i = 4)

Conclusion

You should use pure function instead of impure function as possible. It's more simple to implement and make your code less error prone.