Pure Functions
Side-effect function is a function that, during execution, can change or use global variables, change the values of reference arguments, perform I/O operations, etc.
const dirtyMultiply = (array, value) => {
for (let i = 0; i < array.length; i += 1) {
array[i] = array[i] * value;
}
};
const numbers = [1, 2, 3, 4, 5];
dirtyMultiply(numbers, 2);
// The original data - the numbers array - underwent mutation
console.log(numbers); // [2, 4, 6, 8, 10]
The dirtyMultiply(array, value)
function multiplies each element of the array
array by the number value
. It modifies (mutates) the original array by reference.
Pure function is a function with the result depending only on the values of the passed arguments. With the same arguments, it always returns the same result and has no side effects, that is, it does not change the values of the arguments.
Let's code a pure function for multiplying array elements that returns a new array without changing the original one.
const pureMultiply = (array, value) => {
const newArray = [];
array.forEach(element => {
newArray.push(element * value);
});
return newArray;
};
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = pureMultiply(numbers, 2);
// There is no mutation in the original data
console.log(numbers); // [1, 2, 3, 4, 5]
// The function returns a new array with modified data
console.log(doubledNumbers); // [2, 4, 6, 8, 10]