Last Updated : 17 Dec, 2024
A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed.
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
console.log(add(2, 3));
Characteristics of Pure FunctionsNote: Generally, we use the Pure function in JavaScript for any purpose.
Here, increment is not a pure function because it modifies the external variable count.
JavaScript
let c = 0;
function inc() {
c++;
return c;
}
console.log(inc());
console.log(inc());
Impure Functions: What to Avoid
Impure functions produce unpredictable results or affect external states, which can lead to bugs and make your code harder to test.
JavaScript
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);
{ name: 'Meeta', age: 26 } 26Real-World Applications of Pure Functions
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4