FlashcardNot attempted
What is a closure?
Recall it before you reveal
What is a closure, and name three real uses beyond counters.
Space to reveal
Show answer & explanation
A closure is a function bundled with the lexical environment it was created in: it keeps access to outer variables even after the outer function has returned.
- Data privacy: module pattern, private state (
createCounter) - Function factories / partial application:
curry,partial,memoize,once - Callbacks that need context: event handlers, timers, and React hooks (
setStatecloses over its hook index)
Cost: everything the closure references stays alive, so a long-lived closure over big data is a memory leak.