javascriptnotesFunctional Programming Principles

Pure Functions

pure function in JavaScript (and in functional programming in general) is a function that:

  1. Always produces the same output for the same inputs.
  2. Has no side effects. This means the function does not modify any external state (like global variables, or the DOM).
function add(a, b) {
  return a + b;
}

Given the same inputs, add(2, 3) will always return 5. It does not modify any external state.

Impure Functions

An impure function is the opposite of a pure function. It may produce different outputs for the same inputs or have side effects.

Examples of side effects include:

  • Modifying global variables
  • Changing the state of the program (e.g., updating the DOM)
  • Performing I/O operations (e.g., logging to the console, making network requests)
let counter = 0;
 
function incrementCounter() {
  counter++;
  return counter;
}

This function modifies the external counter variable and will return different values each time it is called.

Safe Functions

The term safe function isn’t as commonly used or as strictly defined as pure/impure functions, but it generally refers to functions that:

  1. Handle errors gracefully (e.g., using try/catch).
  2. Validate their inputs before performing operations.
  3. Do not cause side effects that could lead to unexpected behavior or crashes.

A safe function ensures robustness and predictability, reducing the likelihood of runtime errors or unexpected states.

Idempotent Functions

An idempotent function is one that, no matter how many times it is called with the same input, produces the same result and has the same effect. The concept is often used in the context of HTTP methods, but it applies to functions in general.

Here’s an example of an idempotent function:

function setUserStatus(user, status) {
  user.status = status;
}

If setUserStatus(user, 'active') is called multiple times, the user object’s status will always be set to 'active'without causing additional changes beyond the first call.