2Minutes: Pure Functions In JavaScript
Pure functions are functions that have no dependency on mutable external state or execution context, and adhere to two strict rules: determinism (same inputs produce the same output) and zero side effects.
Determinism
Same input always yields same output:
function sum(a, b) {
return a + b;
}
function randomSum(a, b) {
return a + b + Math.random();
}
console.log(sum(5, 5)); // Always gives 10 => Pure Function
console.log(randomSum(5, 5)); // We cannot predict same output every time => Impure FunctionZero Side Effects
Pure functions alter no data outside of its lexical scope:
// Impure: Mutates the argument passed by reference (External Mutation)
function addItemImpure(cart, item) {
cart.push(item); // Side effect: alters the caller's array in memory
return cart;
}
// Pure: Leaves the original intact and returns a new reference
function addItemPure(cart, item) {
return [...cart, item]; // No side effects, deterministic
}That’s 2Minutes, see you in the next time !
Sources
GeeksForGeeks: https://www.geeksforgeeks.org/javascript/pure-functions-in-javascript/
freeCodeCamp: https://www.freecodecamp.org/news/what-is-a-pure-function-in-javascript-acb887375dfe/
dev.to: https://dev.to/keevcodes/pure-functions-in-react-2o7n