Saturday, June 29, 2024

Pure function in JavaScript

A pure function in JavaScript is a function that always returns the same result given the same input and doesn't have any side effects. This means it doesn't modify anything outside its scope, like global variables or objects passed by reference. Pure functions are predictable, making code easier to understand and test.

Conditions for pure function in JS

A pure function has the following characteristics:

1. Deterministic: For the same input, it always returns the same output. This means the function does not rely on any external state or variables that might change.

2. No Side Effects: The function does not cause any observable side effects. This includes:
  • Not modifying any external variables or state (such as global variables, objects, or arrays passed by reference).
  • Not performing any I/O operations (like logging to the console, writing to a file, or making network requests).

Example of a pure function in JavaScript:
function add(a, b) {
  return a + b;
}

// Calling add with the same arguments will always return the same result
console.log(add(2, 3)); // Output: 5
console.log(add(2, 3)); // Output: 5
Example of an impure function:
let counter = 0;
function incrementCounter() {
  counter += 1;
  return counter;
}

// Calling incrementCounter will return different results due to changing external state
console.log(incrementCounter()); // Output: 1
console.log(incrementCounter()); // Output: 2
To summarize, a pure function adheres to the following conditions:
  • Always produces the same output for the same input.
  • Has no side effects.

No comments:

Post a Comment

Hot Topics