Skip to main content

Pure and Impure functions

Pure function

A pure function is a function that follows these two rules:

  • It does not have side effects like HTTP requests or data manipulation (when a function changes elements that are outside of its scope)
  • It always returns the same output for the same input

Examples of side effects:

We could say that side effects are operations unrelated to calculating the final output:

  • HTTP requests
  • console.log
  • DOM manipulation
  • Mutation input data of a function
  • Modifying data located outside of a function

Example of Pure function

const sum = (a, b) =>  { 
return a + b;
}

In this case, sum is a pure function because:

  • It always returns the same result with the same pair of inputs (deterministic).
  • It does not modify outside variables or states or affect the system in any observable way beyond returning a value (no side effects).

Impure function

An impure function is a function that has side effects. This means the function can modify data outside of its own scope, or interact with the external environment in a way that affects the program's state.

let counter = 0;

function incrementCounter() {
counter += 1; // Modifies the external variable 'counter'
console.log(counter); // side effect
}

incrementCounter(); // 1
incrementCounter(); // 2

Summary

  • A pure function is a function that follows these two rules: it does not have side effects, and it always returns the same output for the same input.
  • Side effects are operations unrelated to calculating the final output inside the function.
  • An impure function is a function that has side effects.