Skip to main content
← JavaScript Lesson 2 / 5

Closures & Scope

A closure is a function that remembers the variables from where it was created. Make a few counters and watch — each one keeps its own private count. They never step on each other.

The factory

function makeCounter() {
  let count = 0;          // private to THIS call
  return () => ++count;   // the returned fn closes over `count`
}

const a = makeCounter();  // fresh scope, its own count
const b = makeCounter();  // a SECOND, independent scope
a(); a(); // -> 2     b(); // -> 1   (they never collide)

Every call to makeCounter() builds a brand-new count and hands back a function that remembers it.

No counters yet. Hit Create counter to call the factory.

Scope chain

Create a counter to see its private scope appear here.

When ++count runs, JS first looks for count in the function's own scope → not found → then in the enclosing makeCounter() scope, where it lives. That outward walk is the closure.

Takeaways

  • A closure = a function + the variables where it was defined.
  • Each factory call makes a fresh, independent scope.
  • Variable lookup walks outward — the scope chain.
  • Closures are how JavaScript does private state.