Closures

Intermediate · 11 min

Why an inner function keeps access to an outer function's variables after it returns — private state, memoization, and the loop-variable bug.

Before thisFunction Declarations, Expressions, and Arrow FunctionsVariables, Scope, and Hoisting

Bro Code · 11 min

Closures

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Bro CodeReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A closure is what you get automatically whenever an inner function is defined inside an outer one: the inner function keeps a live reference to the outer function's variables, and that reference survives even after the outer function has already returned.
  • This isn't a special feature you turn on — it's a direct consequence of lexical scoping, the same rule that lets any nested function see variables from the scope it was written inside. "Closure" is just the name for what that rule produces once the outer function has finished running and the inner one hasn't.
  • Closures are the mechanism behind private state in JavaScript: a variable declared inside a function is invisible from outside it, but a closure returned from that function can still read and update it — giving you a value nothing outside can reach directly.
  • The same mechanism backs memoization (caching results keyed by past inputs, held in a variable the returned function can see) and partial application (returning a new function that has already "remembered" some of its arguments, ready to take the rest later).
  • The classic bug: a `var` loop variable is shared by every callback created inside that loop, so by the time they run, they all see its final value — not the value at the iteration that created them. Switching the loop variable to `let` fixes it, because `let` creates a fresh binding for every iteration instead of reusing one.

The behavior that needs a name

function makeCounter() {
  let count = 0;
  return function () {
    count++;
    return count;
  };
}

const counter = makeCounter();
counter(); // 1
counter(); // 2

makeCounter runs, returns its inner function, and finishes — by every normal intuition about functions, count should be gone the moment makeCounter returns. It isn’t. The inner function keeps incrementing the same count across calls, years after makeCounter itself last ran. That’s a closure: the inner function closed over count, and because something still needs that variable, the engine keeps it alive instead of discarding it with the rest of makeCounter’s now-finished call.

It’s lexical scoping, not a special case

Closures aren’t a separate feature bolted onto the language — they fall directly out of a rule you already rely on constantly: a function can see variables from the scope it was written inside, no matter where it later gets called from. Nested functions seeing their parent’s variables is just normal scoping. “Closure” is the name for what that same rule produces once the parent function has already returned and the child keeps running — the reference doesn’t expire just because the outer call is over.

What this buys you in practice

Private state. A variable declared inside a function is invisible to anything outside it — there’s no syntax to reach in and grab count directly from outside makeCounter. A closure returned from that function is the one sanctioned way in and out, which is the entire mechanism behind “private” data in plain JavaScript functions, no class or special keyword required.

Memoization. A cache of previously computed results has to live somewhere the function can reach on every call, but that nobody else can tamper with. A closure over a Map created once, outside the function that does the real work, is exactly that: created once, read and updated on every subsequent call, invisible to the outside.

Partial application. A function that takes some arguments now and returns a new function waiting on the rest (add(2) returning a function that adds 2 to whatever it’s later called with) needs to remember the arguments it already received. A closure over those first arguments is what makes that remembering possible — the returned function keeps access to them indefinitely.

The loop-variable bug

This is the closure gotcha almost everyone runs into at least once:

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
// logs: 3, 3, 3

Every callback here closes over i — but with var, there’s only ever one i for the entire loop, shared by all three callbacks. None of them run until after the loop has finished (that’s what setTimeout with a delay of 0 still means — it waits for the current code to finish first), and by then i has already reached 3. All three closures are looking at the same variable, and that variable’s final value is 3.

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
// logs: 0, 1, 2

Swapping var for let fixes it with no other change, because let is scoped per iteration of the loop — each pass gets its own fresh i, and each callback’s closure captures that iteration’s own value instead of a single value shared across all of them. This is the clearest real-world demonstration that closures capture variables, not snapshots of values — what you get back depends entirely on how many distinct bindings actually existed to close over.

Where this fits

Closures lean on both function expressions and arrow functions (the inner function needs to be defined somewhere, usually as one of those two) and variables, scope, and hoisting (the let-vs-var loop behavior above is really a scoping rule, closures just make it visible). This is also the last stop before leaving the “Functions and this” group — the event loop, generators, and much of the asynchronous-JavaScript material later in this roadmap depend on closures quietly keeping variables alive across callbacks, exactly as shown above.

Check yourself

  1. 01Why does a function returned from inside another function still have access to that outer function's local variables, even after the outer call has finished?

    Because of lexical scoping: the inner function was written inside the outer one, so it keeps a reference to that scope from the moment it's created, not just while the outer function happens to still be running. The engine keeps that scope alive for as long as something — the inner function — still needs it, instead of discarding it the moment the outer function returns.

  2. 02How do closures give you "private" variables in JavaScript, when the language has no dedicated private-variable keyword for regular functions?

    A variable declared inside a function is already unreachable from outside it by normal scoping rules — nothing outside that function can name it directly. A closure returned from that function (say, a getter and setter pair) keeps the one legitimate path in and out of that variable, so outside code can interact with it only through the interface the closure provides, never by reaching in directly.

  3. 03What specifically goes wrong in this code, and why: `for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }`?

    All three callbacks print `3`, not `0`, `1`, `2` as you'd expect. `var` doesn't create a new `i` for each loop iteration — there's exactly one `i` for the whole loop, and all three arrow functions close over that same single variable. By the time any of them actually runs (after the loop has finished), `i` has already reached `3`, which is what every one of them sees.

  4. 04Why does changing `var i` to `let i` fix the loop-variable bug above, without changing anything else about the code?

    `let` is scoped per-iteration — the loop creates a brand-new `i` binding for every pass through, each with its own captured value, instead of one shared binding for the whole loop. Each callback's closure then captures its own iteration's `i`, so they print `0`, `1`, `2` as expected.

  5. 05What's the connection between memoization and closures?

    A memoized function needs somewhere to store results it has already computed, keyed by the inputs that produced them — usually an object or `Map` created once, outside the function that does the actual work. A closure is exactly what lets the returned, memoized function keep reading and writing that cache on every call, even though the cache was created in an outer scope that ran only once, when the memoized function itself was set up.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark