JavaScript Closures

A closure is a function together with access to variables from its surrounding lexical scope. Because that access is retained after the outer function finishes, closures enable patterns such as private state, callbacks, and function factories.

In JavaScript, functions use lexical scoping: when a function is created, its code is associated with the surrounding scope where it was defined. If the function refers to variables from that scope, it can continue accessing them later.

This commonly appears when an outer function returns an inner function. The outer call has completed, but the inner function still has access to variables declared by the outer function. JavaScript keeps the needed lexical environment available while it is reachable.

Closures are especially useful for encapsulating state. Multiple calls to an outer function can create separate environments, so each returned function can have its own independent variables.

Closures also appear naturally in event handlers, timers, array callbacks, and other functions passed around as values. A common interview point is that a closure is not a special syntax feature; it is a consequence of functions retaining access to their lexical environment.

Key points

Interview questions

Why does the counter returned from a function keep its value?

The returned function refers to the outer function's `count` variable. That reference creates a closure over the variable's lexical environment. Because the returned function remains reachable, the environment containing `count` remains usable, so later calls update the same binding.

Are closures useful for private variables?

Yes. A closure can keep a variable accessible to selected functions while preventing direct access through an ordinary global or object property. For example, a factory can create a private value and return methods that read or modify it. This provides encapsulation using lexical scope.

Do closures capture values or variables?

A closure retains access to lexical bindings rather than simply taking an immutable snapshot of their values. If the captured binding changes, later execution can observe the updated value. This distinction is important when several callbacks share a variable.

What is a closure in JavaScript?

A closure is a function that retains access to variables from the lexical scope where it was defined. This access can remain available even after the outer function has finished executing. Closures are commonly used for callbacks and private state.