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

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.

How many times we going to call, it is going to return the same output.

Last updated

Was this helpful?