Pure Functions

Expert-Level Explanation

A pure function in JavaScript is a specific kind of function that always produces the same output given the same input and does not cause any observable side effects like modifying global objects or state.

Creative Explanation

Imagine a pure function as a vending machine. For the same selection (input), it always gives you the same snack (output), and it doesn't change anything else around it (no side effects).

Practical Explanation with Code

// Pure function
function add(a, b) {
  return a + b; // Always returns the same output for the same inputs
}

console.log(add(2, 3)); // 5
console.log(add(2, 3)); // 5, same output as before

Real-world Example

A pure function is like a mathematical equation, e.g.,y = 2x + 3. For the same value of x, you always get the same y, and the equation does not interact with the world outside itself.