JavaScript Functional JavaScript Pure Functions


Example

A basic principle of functional programming is that it avoids changing the application state (statelessness) and variables outside it's scope (immutability).

Pure functions are functions that:

  • with a given input, always return the same output
  • they do not rely on any variable outside their scope
  • they do not modify the state of the application (no side effects)

Let's take a look at some examples:


Pure functions must not change any variable outside their scope

Impure function

let obj = { a: 0 }

const impure = (input) => {
  // Modifies input.a
  input.a = input.a + 1;
  return input.a;
}

let b = impure(obj)
console.log(obj) // Logs { "a": 1 }
console.log(b) // Logs 1

The function changed the obj.a value that is outside it's scope.

Pure function

let obj = { a: 0 }

const pure = (input) => {
  // Does not modify obj
  let output = input.a + 1;
  return output;
}

let b = pure(obj)
console.log(obj) // Logs { "a": 0 }
console.log(b) // Logs 1

The function did not change the object obj values


Pure functions must not rely on variables outside their scope

Impure function

let a = 1;

let impure = (input) => {
  // Multiply with variable outside function scope
  let output = input * a;
  return output;
}

console.log(impure(2)) // Logs 2
a++; // a becomes equal to 2
console.log(impure(2)) // Logs 4

This impure function rely on variable a that is defined outside it's scope. So, if a is modified, impure's function result will be different.

Pure function

let pure = (input) => {
  let a = 1;
  // Multiply with variable inside function scope
  let output = input * a;
  return output;
}

console.log(pure(2)) // Logs 2

The pure's function result does not rely on any variable outside it's scope.