sajad torkamani

In a nutshell

A pure function is a function with the following characteristics:

  1. It has no side-effects. It doesn’t change any objects or variables that existed before it was called.
  2. Given the same inputs, it’ll always return the same output.

Example of a pure function

function triple(number) {
  return number * 3;
}

This function is pure because:

  1. It doesn’t change any variable or object in the outer scope.
  2. Given the same number argument, it’ll always return the same value.

Example of an impure function

let someVar = 'foo'

function triple(number) {
  someVar = 'bar'
  return number * 3;
}

This function is impure because:

  1. It causes a side-effect – mutates someVar which is part of the outer scope.

Another example of an impure function

const isMonday = new Date().getDay() === 1

function triple(number) {
  if (isMonday) {
    return number * 3 + '!!!'
  }
  
  return number * 3;
}

This function is impure because:

  1. Given the same number input, its output is unpredictable. It could be different depending on the value of isMonday.

Sources