Learn JavaScript
❯ functions.closures

Closures in JavaScript

$concept

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.

$how it works
1

Functions remember birth scope

An inner function returned outward still sees its creator's locals — lexical scope outliving execution.

2

Private state pattern

function counter() { let n = 0; return () => ++n; } — n is accessible only through the returned function.

3

Fresh bindings per call

Each counter() invocation creates independent n — closures capture variables, not values, per creation.

4

Retention costs

Live closures keep their entire scope chain alive — avoid closing over huge objects you don't need.

$example
function counter() {
let n = 0;
return () => ++n;
}
let c = counter();
console.log(c(), c());
Output
1
2
1counter() runs once, creating n = 0 and returning an arrow closing over it.
2c() increments the retained n to 1, then to 2 — state persisting between calls with no object in sight.
3Private, persistent, and unreachable except through c — encapsulation via closure.
$use cases
Private state without classes (counters, memo caches, registries)
Event handlers remembering setup-time configuration
Partial application and currying (multiplier(2) returning doublers)
Module pattern scoping before ES modules existed

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.