Closures in JavaScript
A closure is a function bundled with its lexical environment — inner functions retain access to outer variables after the outer function returns. Counters, private state, memoizers, and event handlers all work because the closed-over variables stay alive exactly as long as something references them.
Each call creates fresh bindings (two counters don't share), and closures retain whole scopes — accidentally holding giant objects through one captured variable is the classic memory pattern to watch. Mastering closures means mastering JavaScript modules, callbacks, and state encapsulation.
Functions remember birth scope
An inner function returned outward still sees its creator's locals — lexical scope outliving execution.
Private state pattern
function counter() { let n = 0; return () => ++n; } — n is accessible only through the returned function.
Fresh bindings per call
Each counter() invocation creates independent n — closures capture variables, not values, per creation.
Retention costs
Live closures keep their entire scope chain alive — avoid closing over huge objects you don't need.
function counter() { let n = 0; return () => ++n;}let c = counter();console.log(c(), c());Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.