Described below are the important distinctions of Pure and Impure functions.
Pure function
- Returned value depends on the values of the arguments
- Pure functions do not call other systems or applications such as network or database calls
- They do not use other variables besides their arguments
- They are independent and only calculate a new value from its arguments
- Pure functions will always return the same result given the same arguments
- they also do not modify the arguments
- Returns a new object
// Pure functions
function double(x) {
return x + x;
}
function doubleAll(list) {
// given an array it will not modify the array it will return a new object
return list.map(double);
}
Impure function
- Impure functions call some external system or application such as a database or network call
- They reach out to other properties of the system or application
- Modify the arguments passed to function
- Returns same object or modified version of same object
// Impure functions
function double(x) {
networkCall(x);
return x + x;
}
function doubleAll(list) {
for (let i = 0; i < list.length; i++) {
list[i] = double(list[i]);
}
return list;
}