Lesson 23 / 38

Closures

Functions that remember their environment.

What is a closure?

A closure is a function that remembers the variables from where it was created, even after that outer function has returned.

A counter with closures

Each call to makeCounter() creates its own private count that only the returned function can touch.

function makeCounter() {
  let count = 0;
  return function () {
    count += 1;
    return count;
  };
}
const counter = makeCounter();
console.log(counter());  // 1
console.log(counter());  // 2

A private backpack

Think of a closure as a backpack the inner function carries — it packs the variables it needs from the outer scope and keeps them, private, wherever it goes.

Quick check: In the counter example, why does calling counter() a second time return 2, not 1?

  • Because count resets every call
  • Because the closure keeps count alive between calls
  • Because JS caches the last return value
Answer

Because the closure keeps count alive between calls — The inner function closes over `count`, so it persists across separate calls to `counter()`.