Open In App

What are Pure Functions in JavaScript ?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, a pure function is a function that always produces the same output for the same input and has no side effects. In other words, pure functions do not modify state outside their scope, such as modifying global variables, changing the state of objects passed as arguments, or performing I/O operations. Pure functions are deterministic, meaning they rely solely on their input parameters to compute their output and do not depend on any external state.

Characteristics of Pure Functions:

  1. Deterministic: Given the same input, a pure function always returns the same output, making its behavior predictable and consistent.
  2. No Side Effects: Pure functions do not modify variables outside their scope, mutate objects passed as arguments, or perform I/O operations such as reading from or writing to files, databases, or the network.

Example: Here, the add() function is a pure function because it takes two input parameters (a and b) and returns their sum (a + b). It does not modify any variables outside its scope or rely on any external state.

Javascript




function add(a, b) {
  return a + b;
}
 
console.log(add(2, 3)); // Output: 5


Output

5

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads