Pure function and Impure functions in JS

Pure function and Impure functions in JS

In JavaScript, a pure function is a function that always returns the same output for the same input and does not cause any side effects. In other words, it only depends on its input parameters and does not modify any external state or global variables. Pure functions are deterministic, meaning that they will always produce the same output given the same input, which makes them easy to test, maintain, and reason about.

Here's an example of a pure function:

function add(a, b) {
 return a + b;
}

This function takes two input parameters and always returns the same output for the same input, without modifying any external state or variables. It does not cause any side effects.

On the other hand, an impure function is a function that can cause side effects and modify external state or global variables. This makes it harder to predict and reason about, and it can lead to bugs and unexpected behavior. Examples of impure functions include functions that modify the DOM, interact with external APIs or databases, and generate random numbers.

Here's an example of an impure function:

let counter = 0

function increment() {
 counter++;
 console.log(counter);
};

This function modifies the external counter variable and logs the updated value to the console. This makes it impure because it causes a side effect and modifies the external state.


Onkar Methekar

Senior Manager IT @ JSW Cement | SAP, Process Improvement

1y

Good one Akshay your posts are definitely help fresher to upskills ,enhance coding and programming Skills..

Hello Akshay... We post 100's of job opportunities for developers daily here. Candidates can talk to HRs directly. Feel free to share it with your network. Visit this link - https://jobs.hulkhire.com And start applying.. Will be happy to address your concerns, if any

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics