JSworkingevergreen

Closures and the module pattern

Functions that remember.

A closure is a function bundled with the variables it was born in β€” the foundation of private state, factories, memoization, and the classic module pattern.

What a closure actually is

A closure is a function plus the lexical scope it was defined in. When an inner function references a variable from an enclosing function, that variable stays alive after the outer function returns β€” the inner function keeps a live reference to it, not a copy. This is what lets a returned function "remember" values long after the call that created it has finished.

Private state without classes

Variables declared inside a factory are invisible to the outside world; only the functions you return can touch them. That gives you genuine encapsulation β€” no _private naming convention to politely ignore, no #fields, just scope. The returned object exposes behaviour while the data stays sealed in the closure.

Factories beat shared mutable globals

Each call to a factory creates a fresh scope, so each returned function gets its own independent state. Two counters from the same factory never interfere. This is the cleanest way to mint many small stateful things β€” counters, sequence generators, rate limiters β€” without a single shared variable.

The revealing module pattern

Wrap a body of private helpers in a function, then return an object literal that "reveals" only the public ones. The classic form is an IIFE (immediately-invoked function expression) that runs once and hands back the public surface β€” a singleton module with private internals. The same shape, returned from a named factory instead of an IIFE, gives you reusable instances.

Try it 5 examples

A counter factory

JSintro
Press Run to execute

a ends at 2 and b at 99 because each makeCounter call closes over its own count β€” proof that the two counters hold completely independent state.