Pure Functions

In JavaScript, a pure function is a function that always produces the same output given the same input and has no side effects.

Illustration of Pure Functions
Illustration of Pure Functions

💡 Key Characteristics of Pure Functions

  • Deterministic: Always returns the same result for the same arguments.
  • No Side Effects: Does not modify external state or data.

Pure functions are predictable, easier to test, and enable functional programming patterns.

Pure vs Impure Functions
Pure FunctionImpure Function
Returns consistent output for same inputsOutput may vary despite same inputs
No modification of external variablesModifies external state or variables
No side effects (e.g. no I/O, no DOM changes)Has side effects like API calls, DOM manipulation
Easier to test and debugHarder to test due to hidden dependencies

📌 Deep Dive: Example of a Pure Function

JAVASCRIPT
function add(a, b) {
  return a + b;
}
Output
add(2, 3) // 5

This function always returns the sum of a and b without changing anything outside itself.

📌 Deep Dive: Example of an Impure Function

JAVASCRIPT
let count = 0;

function increment() {
  count++;
  return count;
}
Output
increment() // 1
increment() // 2

This function changes the external variable count, so it is not pure.

⚠️ Why Avoid Side Effects?

Side effects make functions unpredictable and harder to debug because changes happen outside the function scope.

Pure functions help keep code more reliable and easier to reason about, especially in complex applications.

💡 Summary

  • Pure functions return values based only on input parameters.
  • They never modify variables or data outside their scope.
  • They make your code more testable and maintainable.