Pure Functions in JavaScript (original) (raw)

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));

`

**Note: Generally, we use the Pure function in JavaScript for any purpose.

Characteristics of Pure Functions

Example of a Function with Side Effects

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);

``

Output

{ name: 'Meeta', age: 26 } 26

Real-World Applications of Pure Functions