JavaScript·Intermediate·Coding·1 min read
What is a closure, precisely?
Short interview answer
A closure is a function together with the lexical environment in which it was created. The function keeps access to the bindings it references from that environment even when it executes outside the creating scope. It retains bindings, not frozen copies of their values.
Example
function makeCounter() { let count = 0; // lives in makeCounter's scope return () => ++count; // the returned fn closes over `count`}
const next = makeCounter();next(); // 1next(); // 2 — `count` survived after makeCounter() returnedKey takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.