The definition interviewers want
A closure is a function bundled together with the variables from the scope where it was created. The function keeps access to those variables even after the outer function has returned.
In lesson 1-1 the inner function ran while the outer one was still running. The surprise: it also works after. If outer returns inner, the returned function still carries outer's variables with it. They don't get thrown away.
Closures are not interview trivia. Every event handler that remembers which button it belongs to, every debounced search box, and every React hook works this way: a function needs to remember something between calls without a global variable, and a closure is the tool the language provides for exactly that.
Code exercise · javascript
Run it. `makeCounter` finished long before we call `next()`, yet `count` is still alive. The returned function closed over it.
Each call creates a fresh scope
Every time you call makeCounter(), JavaScript creates a brand-new count. Two counters made by two calls do not share anything:
- The closure captures the variable itself, not a copy of its value.
- Different calls to the maker function capture different variables.
This is how you get private, per-instance state without classes.
Code exercise · javascript
Run it. `a` and `b` come from separate calls, so each has its own private `count`.
Quiz
After `const a = makeCounter(); const b = makeCounter();`, you call `a()` five times. What does the first `b()` return?
Code exercise · javascript
Your turn, a classic interview warm-up. Write `makeAdder(n)` that returns a function which adds `n` to its argument. The logs below must print 8 and 15.
Worked example: run-once functions
A production pattern built from nothing but a closure: some actions must happen at most once — initializing an SDK, charging a card, attaching a global listener. A global alreadyRan flag would work, but any code anywhere could flip it back. Hide the flag in a closure instead: once(fn) returns a wrapped function whose private called flag no outside code can reach or reset.
Code exercise · javascript
Your turn. Implement `once(fn)`: return a function that calls `fn` with its argument the FIRST time, and returns `undefined` on every later call. The flag must be a closed-over variable.