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 object
Ex 2:
// input --> output
function sum(num1, num2) {
return num1 + num2;
}
function multiplyBy2(num) {
return num * 2;
}
// the output is predectable
Every function can't be written as a pure function, because we have difference in data handling things.
It handles with,
1 Task
Predictable
Immutable state
No Shared state
Pure,
return statement
Composable
Idempotence:
The function return the same output how many time you call the function, even it is contact with outside environment. The code output is predictable.
Ex 1:
function notGood(num) {
console.log(num);
}
notGood(5); // 5
Ex 2:
Math.abs(-50); // 50
How many times we going to call, it is going to return the same output.
Last updated
Was this helpful?