// Pure functions
function square(x) {
return x * x;
}
function squareAll(items) {
return items.map(square);
}
Pure functions 's return value depends solely on the values of its arguments. No observable "side-effects" such as network or database calls. Pure functions do not modify the values passed to them. In the second example, the function does not modify the items array, instead creates a new array with map()
.
// Impure functions
function square(x) {
updateXInDatabase(x);
return x * x;
}
function squareAll(items) {
for (let i = 0; i < items.length; i++) {
items[i] = square(items[i]);
}
}