Pure Functions in Javascript
A function is called a pure function if it satisfies the below two conditions:
- Function must return same result when ever you pass same arguments. It should not depend on state of the variables.
- Function must not produce any side effects.
Take a look at the below example:
product(4,6);
function product ( a, b ) {
console.log(a*b);
}
The above function always results 24, when the input parameters are 4 and 6.
A function is not a pure function when it deals with external values. For example, the result of the below function doesn't depend only on its parameters but it also depends on the value of x. Result will get varied when value of x changes which is a side effect.
let x = 10;
function product( y ) {
let num = (x == 10) ? x : 5;
console.log(num*y)
}
product(5)
Here are some of the advantages of writing pure functions:
- Testing is easy as it yields predictable output
- Easy to debug and easy to refactor
- Improves performance as it yields predictable same output all the time without any side effects and thus, the result can be stored in cache.