Impure vs Pure Functions

Pure Functions

A pure function is a function which:

  • Given the same input, will always return the same output.

  • Produces no side effects.

Pure Functions Produce No Side Effects

A pure function produces no side effects, which means that it can’t alter any external state.

Immutability

JavaScript’s object arguments are references, which means that if a function were to mutate a property on an object or array parameter, that would mutate state that is accessible outside the function. Pure functions must not mutate external state.

Consider this mutating, impure `addToCart()` function:

const addToCart = (cart, item, quantity) => {
  cart.items.push({
    item,
    quantity
  });
  return cart;
};

Last updated