What are Pure Functions in JavaScript?
A pure function consistently returns the same result given the same input and does not cause any side effects. In other words, pure functions don’t modify states outside of their scope, for example, modify the global variable, changing in objects passed as argument means don’t depend on any external state.
Characteristics of Pure Functions
- Same Input, Same Output: Every time gives the same output for the same input, making its behavior predictable, consistent, and easily testable.
- No Side Effects: Don’t modify their outside scope variable, pass mutable objects as arguments, performing Input/Output operations such as writing or reading from disk/file or database or network.
Here, the sum() function is a pure function because it takes the same input as parameters (a and b) and produces the sum of (a+b) as output every time. This function does not modify any variable outside its scope or does not depend on any external state.
function sum(a, b) {
return a + b;
}
console.log(sum(5, 6)); // Output: 11
Output:
11