JavaScript ยท Chapter 54 of 55

JavaScript Closures

A closure is a function that remembers the variables from its outer (enclosing) scope, even after that outer function has finished executing.

Closures are the mechanism behind many powerful patterns, including private variables, memoization, and function factories.

How closures work

When a function is defined inside another function, it 'closes over' the variables of the outer function, keeping access to them even after the outer function returns.

Practical uses

Closures enable private state (data hidden from outside access) and function factories that generate customized functions.

Example 1 (javascript)
function makeCounter() {
  let count = 0;
  return function() {
    count++;
    return count;
  };
}
let counter = makeCounter();
console.log(counter());
console.log(counter());
Output
1
2

The returned function remembers and updates count even after makeCounter finished running.

Example 2 (javascript)
function multiplier(factor) {
  return num => num * factor;
}
let triple = multiplier(3);
console.log(triple(5));
Output
15

triple 'remembers' factor=3 from when multiplier was called.

Key points

  • A closure lets a function access its outer scope's variables later.
  • Closures persist even after the outer function has returned.
  • They enable private state and function factories.
  • Every JavaScript function forms a closure over its defining scope.
๐Ÿ’ก Note: Closures are why counters, debounce functions, and memoization utilities work in JavaScript.

๐Ÿ“ Quick Quiz

1. What is a closure?

2. Do closures persist after the outer function returns?

3. Which pattern relies heavily on closures?