Pure function
A function has to always return the same output, given the same input and a function cannot modify outside by itself and no side effects.
Ex 1:
// side effect (data modified outside the function)
const array = [1, 2, 3, 4, 5];
function mutateArray(arr) {
arr.pop();
}
mutateArray(array); // [1, 2, 3, 4];
mutateArray(array); // [1, 2, 3];
// no side-effect
const array = [1, 2, 3, 4, 5];
function removeLastItem(arr) {
const newArr = [].concat(arr);
newArr.pop();
return newArr;
}
const newArr = removeLastItem(array);
console.log(newArr); // [1, 2, 3, 4];
console.log(array); // [1, 2, 3, 4, 5]; // original data is not affected
// immutable objectIdempotence:
Last updated