In JavaScript, a pure function always returns the same result if the same arguments are passed in the function. It does not depend on any state or data change during a program’s execution. Instead, it only depends on its input arguments.
A pure function does not produce any observable side effects, such as network or database calls or modifying the input arguments. Pure functions are atomic building blocks of functional programming in JavaScript, which breaks the application into small chunks called functions and methods. Each function or method has a particular role in the application.
It only maps the input values to the output values.
This programming style is procedural programming because It is a sequence of operations performed on the input to that function.
The function can access only those variables passed to that function as a parameter.
A global variable or an instance of a class is not considered a legitimate variable inside any Pure Function.
The global scope of a variable is not used in producing Pure Functions.
It’s a set of instructions that behave as Mathematical Functions.
It’s a role-based function whose only task is to take an argument, perform some operations on that variable and then return it.
Example of an impure function
let counter = 0;
function increment() {
// Modifies the external variable 'counter', causing a side effect
counter++;
return counter;
}
// The output depends on the external variable 'counter'
// and the function has a side effect.
console.log(increment()); // Output: 1
console.log(increment()); // Output: 2
Output
1
2
Example of a pure function
function add(a, b) {
return a + b;
}
// The output will always be the same for the same input arguments.
console.log(add(2, 3)); // Output: 5
Output
5
In functional programming, pure functions are preferred over impure functions because they promote more accessible code to reason about, test, and maintain.
That’s it.