Closures & Encapsulation
Use lexical scope to keep state private, build small utilities, and recognise when a closure costs more than it gives.
By the end, you’ll be able to…
- Explain how a function retains access to its lexical environment.
- Build a factory that exposes behaviour while keeping state private.
- Implement once and debounce helpers with closures.
- Identify retained memory and choose a clearer tool when a closure is unnecessary.
01Functions remember where they were born
A closure is a function together with the lexical environment in which it was created. That environment contains the bindings the function can see: parameters, local variables, and names from enclosing scopes. When an inner function is returned from an outer function, it keeps a reference to those bindings even after the outer call has finished. The function does not carry a copy of the values; it carries access to the variables themselves.
This is why a counter can survive between calls. Each call to the factory creates a fresh environment with its own count variable. The returned methods share that environment, so increment and read see the same number. Two counters created by two calls have separate environments and cannot interfere with each other. The state is private because nothing outside the returned object has a name for it.
02Factories with private state
A factory is a function that returns a new object or function. When the factory closes over variables, the returned API can enforce rules that public properties could not. For example, a cart factory can expose add and count while keeping its items array unreachable. Callers cannot push arbitrary values into the array or reset the count without using the provided methods.
The module pattern applies the same idea at file level: an IIFE holds private variables and returns an object of public functions. With ES modules, the file itself already provides private scope, so a top-level const is invisible to importers unless exported. Reach for a factory when you need several independent instances; reach for module scope when one shared instance is enough.
03Small utilities built on closures
Closures are ideal for wrapping a function with a small amount of memory. once(fn) returns a wrapper that runs fn only on the first call and returns the cached result afterward. A called flag lives in the closure, so every caller shares the same decision. This is useful for one-time initialization, analytics events, or expensive setup that must not repeat.
debounce delays a function until calls have stopped for a set time. The wrapper keeps a timer id in its closure, clears the previous timer on each call, and starts a new one. Only the final call in a burst reaches fn. Both utilities preserve the arguments they receive. Neither needs a class, a global variable, or a custom event system.
04Memory and judgment
A closure keeps its environment alive. Usually that environment is tiny, but a long-lived callback can retain more than intended. A timer that captures a large array, or an event listener that captures a removed DOM subtree, prevents garbage collection for as long as the callback exists. Clear timers, abort listeners, and avoid capturing large objects in handlers that live for the whole page.
Closures are not automatically the best design. If several objects must share one piece of state, module scope or an explicit store is clearer. If you need many instances with a well-defined public shape, a class may communicate that shape better. Use a closure when private state and a small behavioural API are the point, not merely because nested functions look clever.
The ideas worth keeping.
- A closure is a function plus the lexical bindings it can still reach after its outer function returns.
- Factories and module scope keep state private while exposing a small, controlled API.
- Closures power once and debounce, but long-lived callbacks can retain memory and should be cleaned up.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Build an id generator
Write createIdGenerator(prefix) that returns a function. Each call to the returned function increments a private counter and returns a string such as task-1, then task-2. The counter must not be reachable from outside.
Explore a worked solution
function createIdGenerator(prefix) { let next = 0; return function () { next += 1; return prefix + "-" + next; };}const nextTaskId = createIdGenerator("task");console.log(nextTaskId());console.log(nextTaskId());The returned function closes over next and prefix. Every call updates the same private binding, while another generator created by a second call gets its own independent counter.
Exercise 2: Add cancellation to debounce
Rewrite debounce(fn, delay) so the returned function also has a cancel method that clears any pending timer. The wrapper should still call fn with the most recent arguments after the delay.
Explore a worked solution
function debounce(fn, delay) { let timer = null; const wrapped = (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; wrapped.cancel = () => { clearTimeout(timer); timer = null; }; return wrapped;}Both the wrapper and cancel close over the same timer variable. Assigning the timer through the closure lets cancel reach the pending timeout without exposing it to callers.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Build an id generator
Write createIdGenerator(prefix) that returns a function. Each call to the returned function increments a private counter and returns a string such as task-1, then task-2. The counter must not be reachable from outside.
task-1 task-2
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.