Sobes.tech
Middle

What is a pure function? When is a function considered pure? What are side effects?

sobes.tech AI

Answer from AI

A pure function is a function that always returns the same result given the same inputs and does not modify any external state.

A function is considered pure if:

  • It has no side effects (does not modify external variables, does not write to a database, does not perform input/output operations).
  • It does not depend on external state other than the arguments passed to it.

Side effects are any actions of a function that affect the external world or state outside the function itself. For example:

  • Modifying global variables
  • Writing to a database or file
  • Sending network requests
  • Outputting to the console

Example of a pure function in JavaScript:

function add(a, b) {
  return a + b;
}

This function always returns the sum of its arguments and does not change anything outside itself.

Example of a function with a side effect:

let counter = 0;
function increment() {
  counter += 1; // modifies external variable
}

Such a function is not pure.