Programming Language
JavaScript
Advanced JavaScript
Functional Programming
Pure Functions

Pure Functions

A Pure Function is a function that always produces the same output for the same input and has no side effects (it doesn't change anything outside of itself).


1. The Analogy: The Vending Machine

Think of a Vending Machine.

  • Input: You press button B4.
  • Output: You get a Snickers bar.

Every time you press B4, you get a Snickers. The machine doesn't suddenly start playing music, it doesn't charge your credit card for a different item, and it doesn't change the price of other snacks. It’s predictable and self-contained.


2. Coding Example: The Math vs. The Messenger

The Impure Way (Dangerous)

This function depends on and changes an external variable.

let total = 0;
function addToTotal(amount) {
  total += amount; // Side Effect! Changes external state
  return total;
}

The Pure Way (Safe)

This function only cares about its inputs and returns a new value.

function add(a, b) {
  return a + b; // Always returns the same result for the same a and b
}

3. Why it matters in Coding

  1. Testability: Pure functions are incredibly easy to test. You don't need to "set up" a complex database or global state. You just pass an input and check the output.
  2. Caching (Memoization): Because the output never changes for the same input, you can "save" the result and skip the calculation next time.
  3. Concurrency: Multiple parts of your program can call a pure function at the same time without worrying about them "stepping on each other's toes."

Real-Life Coding Scenario: The Formatter

Think of a Date Formatter function. You give it a Date object and a format string, and it returns a formatted string. It doesn't change the original date, and it doesn't update your UI directly. It just does one job and does it perfectly.


Summary

ConceptActionAnalogy
ImpureChanges external worldA person who talks while they work
PureOnly returns a valueA Vending Machine

By using pure functions, you create a system of "lego bricks" that are easy to move, test, and replace!