TExcelTAD
Home › JavaScript › JS Closures

JavaScript Closures

A closure is a function together with the variables it "remembers" from the place where it was created. Even after the outer function has finished running, an inner function can still read and update the outer function's variables. Closures are behind private state, factories, event handlers, memoisation and much more — you've probably used them already without knowing.

A first closure

js · try it yourself
function makeGreeter(greeting) {
  return function (name) {
    return `${greeting}, ${name}!`;     // uses greeting from the outer function
  };
}

const hello = makeGreeter("Hello");
const hola = makeGreeter("Hola");

console.log(hello("Ana"));
console.log(hola("Ana"));
Hello, Ana!
Hola, Ana!

When makeGreeter("Hello") returns, its local variable greeting would normally disappear. But the returned function still refers to it, so JavaScript keeps it alive. Each call to makeGreeter creates a separate greeting, which is why hello and hola behave differently.

Private state: a counter

Closures can keep mutable state that nothing else can touch:

js · try it yourself
function createCounter(start = 0) {
  let count = start;                  // private: only the functions below can see it
  return {
    increment: () => ++count,
    decrement: () => --count,
    value: () => count,
  };
}

const clicks = createCounter();
const lives = createCounter(3);

clicks.increment();
clicks.increment();
lives.decrement();

console.log(clicks.value(), lives.value());
console.log(clicks.count);            // not accessible from outside
2 2
undefined

There's no way to set count to a nonsense value from outside — the only access is through the functions you chose to expose. This is the classic module pattern, used long before JavaScript had classes or #private fields.

Function factories

Closures make it easy to generate specialised functions from a general one:

js · try it yourself
const multiplier = (factor) => (n) => n * factor;
const double = multiplier(2);
const triple = multiplier(3);
console.log([1, 2, 3].map(double), [1, 2, 3].map(triple));

function makeValidator(min, max) {
  return (value) => value >= min && value <= max;
}
const isPercent = makeValidator(0, 100);
const isAdultAge = makeValidator(18, 130);
console.log(isPercent(42), isPercent(140), isAdultAge(17));
[ 2, 4, 6 ] [ 3, 6, 9 ]
true false false

Memoisation

A closure can hold a cache that survives between calls. Here a slow function gets a remembered result for each input it has seen:

js · try it yourself
function memoize(fn) {
  const cache = new Map();
  return (n) => {
    if (cache.has(n)) {
      console.log(`  cache hit for ${n}`);
      return cache.get(n);
    }
    const result = fn(n);
    cache.set(n, result);
    return result;
  };
}

const slowSquare = (n) => {
  console.log(`  computing ${n}²`);
  return n * n;
};

const fastSquare = memoize(slowSquare);
console.log(fastSquare(9));
console.log(fastSquare(9));
console.log(fastSquare(4));
  computing 9²
81
  cache hit for 9
81
  computing 4²
16

Closures capture variables, not values

A closure keeps a reference to the variable itself, so it sees later changes. That's why the loop example below behaves differently with var (one shared variable) and let (a new variable for every iteration):

js · try it yourself
const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);

const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);

console.log(withVar.map((f) => f()));
console.log(withLet.map((f) => f()));

let mood = "happy";
const report = () => `I am ${mood}`;
mood = "sleepy";
console.log(report());       // sees the current value
[ 3, 3, 3 ]
[ 0, 1, 2 ]
I am sleepy

Closures in everyday code

You use closures every time a callback refers to a variable from outside:

html · try it yourself
<button id="like">👍 0</button>
<script>
  function setupLikeButton(button) {
    let likes = 0;                       // remembered by the click handler
    button.addEventListener("click", () => {
      likes++;
      button.textContent = `👍 ${likes}`;
    });
  }
  setupLikeButton(document.getElementById("like"));
</script>

Note: Variables held by a closure stay in memory as long as the closure itself is reachable. That's usually exactly what you want — but long-lived closures (e.g. listeners you never remove) holding large data can cause memory leaks.

Test yourself

What is a closure?

  1. A function that closes the browser window
  2. A function bundled with the variables of the scope where it was created
  3. A function with no parameters
  4. A way to end a loop

Given const add = a => b => a + b;, what is add(2)(5)?

  1. 2
  2. 5
  3. 7
  4. A function

Two counters created by separate calls to createCounter()…

  1. share one count
  2. each have their own count
  3. can't both exist
  4. share count only if declared with var