What is a closure in programming? A closure is a function bundled with references to the lexical environment where it was created. That is why it can keep using outer variables after the outer function has returned.
This essay sits in the programming essays collection. It treats a closure as a function plus its captured environment, builds the same counter as a closure and as an object, and then covers Python and loop surprises. If you are also curious how source text becomes something a language can run, see how does a parser work.
How a closure forms
A closure forms when an inner function uses variables that belong to an outer function. MDN’s guide describes it as a function bundled together with references to its surrounding state, and Turing’s course notes put the same idea as a function that has a reference to its outer lexical environment. The mechanism has a few stages, in this order:
- The outer function runs. It declares local variables and defines an inner function that uses at least one of them.
- The inner function is created. MDN states that in JavaScript closures are created every time a function is created, at function creation time. The environment is attached at that moment.
- The outer function returns. Normally its local variables would disappear with it. Turing’s notes point out that in many languages a variable such as a greeting’s first name would be completely removed from memory once the function finishes, whereas JavaScript keeps what the inner function still references.
- The inner function is called later. It reads, and sometimes updates, the captured variable as if the outer function were still running.
The practical result is that a closure is not just code. It is code plus the specific variables it needs, carried together as one value you can pass around.
Lexical scope and free variables
Lexical scope is the rule that decides which variables a function can see, and it explains why closures work. Turing’s course notes say that in JavaScript the accessibility of a variable is determined by its location in the source code, and nested functions can reach what surrounds them. Where a function is written matters; where it is called from does not.
A free variable is a variable that a function uses but does not declare itself. In a typical closure, the inner function uses variables from the outer function, and those are its free variables. They are what the closure has to carry along, as Mimo’s glossary entry describes for an inner function that uses outer variables.

Think of scopes as nested boxes drawn by the layout of the source. An inner box can look outward through the arrows, never inward. A closure simply keeps those outward arrows alive after the outer box has finished executing.
The same counter as a closure and as an object
A counter shows the equivalence between closures and objects better than any definition. MDN notes that closures have obvious parallels to object-oriented programming, where objects associate data with methods. Mimo makes the same point from the other direction: closures make functions behave more like objects, because they can hold internal state without being classes.

The closure version
Write an outer function, call it makeCounter, that declares a count variable and returns an inner function. Each call to the inner function increases count and hands back the new value. The count variable is a free variable of the inner function, so the closure carries it. Nothing outside can reach count except by calling the returned function.

Calling makeCounter again builds a fresh, independent counter. MDN shows this with its add5 and add10 functions, which share the same function body definition but store different lexical environments. In the first, x is 5; in the second, x is 10.
The object version
Write an object with a count field and an increment method that updates the field and returns it. Creating a second object gives a second independent counter, exactly as a second makeCounter call does. The data and the behavior are bundled together, which is what the closure did without a class.
| Question | Closure counter | Object counter | Planning use |
|---|---|---|---|
| Where does the count live? | In a captured variable of the outer function’s environment | In a field on the object | Both keep state between calls |
| What do you call? | The returned function itself | A method on the object | Pick the style that matches the surrounding code |
| Who can reach the count? | Only the inner function; code outside cannot see it directly | Anything holding the object, through its field or methods | A closure hides the variable by default |
| How do you get another counter? | Call the outer function again for a new environment | Create another object | Each instance has its own state |
The comparison draws on MDN’s closures guide and GeeksforGeeks’ note that closures let a function keep variables private and accessible only within that function.
The equivalence is the point of closures vs objects: a closure is one function with hidden data, and an object is several functions with visible data. Reach for the closure when you need one behavior with some remembered state. An object suits you better when several operations must share the same fields.
Closures in Python
Python closures follow the same rule as JavaScript ones, with one extra keyword when you change a captured variable. In Mimo’s example, an inner add function keeps x available after make_adder has returned, because add() carries it along. Reading a captured name needs no special syntax.
Changing the variable is different. Python requires the nonlocal keyword when modifying a captured variable, as Mimo’s glossary notes. A Python version of the counter therefore declares count nonlocal inside the inner function before increasing it. Leave nonlocal out and the update does not reach the captured variable, so the counter cannot work as intended.
If you are porting the counter from JavaScript, the structure stays identical. Only that declaration is new.
Why closures in loops surprise people
Closures in loops surprise people because a closure holds a reference to a variable, not a snapshot of its value. Mimo observes that in JavaScript, loops once caused surprising behavior because closures captured references, not values. If every callback refers to the same variable, they all see whatever that variable holds when they finally run.
The cause is how var is scoped. MDN explains that variables declared with var are either function-scoped or global-scoped, so a loop that declares its counter with var creates only one variable for the whole loop. GeeksforGeeks gives the classic result: all callbacks share the same i created with var, so the output is 4 4 4.
| Declaration | Scope in the loop | What callbacks see | Planning use |
|---|---|---|---|
| var | Function-scoped or global-scoped, not block-scoped | One shared i, giving 4 4 4 in the example | Avoid for loop counters that callbacks capture |
| let | A new binding for each iteration | Each callback keeps its own i | The simple fix; change the keyword and nothing else |
These behaviors come from MDN’s closures guide and GeeksforGeeks’ closure article, which notes that using let creates a new binding for each iteration.
When you see identical values from callbacks created in a loop, check the declaration keyword first. Switching to let is the least invasive repair.
First-class functions and where closures fit
Closures depend on first-class functions, meaning functions that can be stored in variables, passed as arguments and returned from other functions. Turing’s notes tie closures to functional programming, where functions are treated as first-class citizens. Returning an inner function from an outer one, as in the counter, only works because the function is a value like any other.

That pairing gives you a short rule for choosing a tool. If the job is a single behavior with remembered state, such as a counter or an adder preset with a value, a closure is compact. If the state needs many named operations, an object keeps them together more readably. Data structures show the same trade-off: a table that stores and retrieves values, covered in how do hash tables work, is usually built as an object rather than as a function with hidden state.
Frequently asked questions
Do closures give true privacy?
No. Turing’s course notes state that closures don’t provide true privacy. They hide a variable from ordinary access, and shiftasia describes them as a way to create private variables and functions, but treat that as encapsulation rather than security.
Does a closure copy the variables it uses?
No. It keeps references to them, which is why a later change to a shared variable is visible inside every closure that captured it.
Which languages in this essay support closures?
JavaScript and Python, both shown above. The shape is the same in each: an inner function that uses an outer variable, with Python adding nonlocal when the variable is modified.



