A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed.
- Always returns the same result for the same input, ensuring consistent and predictable behavior.
- Does not modify or rely on any external variables or state.
- Often works with immutable data, which improves reliability and prevents side effects.
- Independent of external state, making functions easy to test and highly reusable.
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
console.log(add(2, 3));
Note: Generally, we use the Pure function in JavaScript for any purpose.
Characteristics of Pure Functions
- Deterministic Output: For a given set of inputs, the output is always the same.
- No Side Effects: The function does not modify variables outside its scope, does not interact with external systems such as APIs, databases, or the DOM, and does not change mutable data.
- Immutability: Pure functions do not change the input values; instead, they return a new value or object.
Function Behavior with Side Effects
Here, increment is not a pure function because it modifies the external variable count.
let c = 0;
function inc() {
c++;
return c;
}
console.log(inc());
console.log(inc());
Impure Functions: What to Avoid
Impure functions can cause unpredictable behavior or modify external state, making code harder to understand and maintain.
- They may return different results for the same inputs.
- They can change or depend on external variables, causing hidden bugs.
let user = { name: "Meeta", age: 25 };
function updated(newAge) {
user.age = newAge;
return user;
}
console.log(updated(26));
// Alters the global `user` object
console.log(user.age);
Real-World Applications of Pure Functions
- Data Transformation: Use pure functions in map, filter, and reduce operations for processing data.
- State Management: Libraries like Redux emphasize pure functions for state updates.
- Unit Testing: Pure functions are ideal for unit tests because they have predictable outputs.
- Performance Optimization: Pure functions are easily memoized, as their outputs depend solely on inputs.