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 :
- Given the same arguments and then return the same output.
- No side effects.
Side effects are like :
- Mutates and rely on outer scope variable to do calculation
- Doing network request
- Print to console
- 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.