Problem Statement
What is a pure function?
Explanation
A pure function has two requirements:
Same input always produces same output. The function is deterministic and predictable.
No side effects. The function does not modify external state, does not mutate arguments, does not perform I/O, and does not change global variables.
Pure functions are easier to test, debug, and reason about.
They enable functional programming patterns like memoization.
Impure functions have side effects or depend on external state.
Pure functions improve code quality and maintainability.
Code Solution
SolutionRead Only
// PURE FUNCTIONS
// Pure - same input, same output, no side effects
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // Always 5
console.log(add(2, 3)); // Always 5
// Pure - doesn't modify input
function double(arr) {
return arr.map(n => n * 2);
}
const nums = [1, 2, 3];
const doubled = double(nums);
console.log(nums); // [1, 2, 3] (unchanged)
console.log(doubled); // [2, 4, 6]
// IMPURE FUNCTIONS
// Impure - modifies external variable
let total = 0;
function addToTotal(value) {
total += value; // Side effect!
return total;
}
console.log(addToTotal(5)); // 5
console.log(addToTotal(5)); // 10 (different output!)
// Impure - modifies argument
function addItem(arr, item) {
arr.push(item); // Mutates input!
return arr;
}
// Impure - depends on external state
function getCurrentTime() {
return new Date(); // Different output each time!
}
// Impure - I/O operation
function logMessage(msg) {
console.log(msg); // Side effect!
}
// Impure - random output
function rollDice() {
return Math.floor(Math.random() * 6) + 1; // Non-deterministic!
}
// MAKING IMPURE FUNCTIONS PURE
// Impure version
function addItemImpure(arr, item) {
arr.push(item);
return arr;
}
// Pure version
function addItemPure(arr, item) {
return [...arr, item]; // Return new array
}
const original = [1, 2, 3];
const newArr = addItemPure(original, 4);
console.log(original); // [1, 2, 3] (unchanged)
console.log(newArr); // [1, 2, 3, 4]
// BENEFITS OF PURE FUNCTIONS
// 1. Easy to test
function multiply(a, b) {
return a * b;
}
console.assert(multiply(2, 3) === 6);
console.assert(multiply(2, 3) === 6); // Always same!
// 2. Memoization (caching)
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (key in cache) {
return cache[key];
}
const result = fn(...args);
cache[key] = result;
return result;
};
}
const expensiveCalc = memoize((n) => {
console.log('Computing...');
return n * n;
});
console.log(expensiveCalc(5)); // Computing... 25
console.log(expensiveCalc(5)); // 25 (from cache, no computing)