A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/pure-functions-in-javascript/ below:

Pure Functions in JavaScript - GeeksforGeeks

Pure Functions in JavaScript

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.

JavaScript
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

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