Course contentsShow
← JavaScript
Lesson 1749 of 2,72337. Functional Programming PatternsFree lesson

Purity and Closures

Understand when closures preserve purity and when they capture mutable state.

Purity and Closures

What you'll learn: How closures can maintain or break function purity depending on what state they capture.

Closures allow a function to "remember" variables from its outer scope. This power can either preserve purity or introduce hidden impurity, depending on what the closure captures and how it's used.

Pure Closures

A closure remains pure when it captures immutable values or never-changing references:

function makeMultiplier(factor) {
  return function(num) {
    return num * factor; // 'factor' is captured but never changes
  };
}

const double = makeMultiplier(2);
double(5); // 10
double(5); // 10 (deterministic, no side effects)

Here, factor is captured once and never mutates. The returned function is pure—same input always produces the same output.

Impure Closures

A closure becomes impure when it captures mutable state that changes over time:

function makeCounter() {
  let count = 0; // mutable captured variable
  return function() {
    return ++count; // reads AND modifies external state
  };
}

const counter = makeCounter();
counter(); // 1
counter(); // 2 (not deterministic—depends on how many times it was called)

The function returns different values for the same (empty) input because it relies on and modifies captured state.

The Distinction

Think of closures like a backpack: if it contains only unchanging supplies (pure), your journey remains predictable. If it contains a growing collection of items (mutable state), your experience changes each time you reach in.

Key Takeaway: Closures preserve purity when they capture immutable values and avoid modifying captured state; they break purity when they read or write mutable variables from their enclosing scope.