DEV Community

Nikunj R. Prajapati
Nikunj R. Prajapati

Posted on

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)