DEV Community

Nikunj R. Prajapati
Nikunj R. Prajapati

Posted on

2 2

Day 2 : What is pure function in JS ?

A pure function is a function which

  • Given the same input, always returns the same output.
  • Produces no side effects.
  • Pure functions must not mutate external state.

A function is only pure if, given the same input, it will always produce the same output.

Example :

PURE FUNCTION
function isValid(age){
  return age >= 18;
}
Enter fullscreen mode Exit fullscreen mode

This function will always return true or false based on age.

EXAMPLE OF UNPURE FUNCTION

  • Pure functions must not mutate external state.
items = [];
const addItems = (item) => {
  items.push({
    item
  }); 
};

Enter fullscreen mode Exit fullscreen mode

addItems() is not a pure function because it mutates the external state by pushing values to that items array.

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay