noteslearnings

Why Is It Called a Closure? A History of Variables Through `let` and `var`

Following the name closure through lexical environments and variable binding, then comparing let and var loops to distinguish names, bindings, and values.

When working with JavaScript, a few questions tend to come up.

Why do for (var i...) and for (let i...) behave differently with closures?
Why wasn’t var block-scoped in the first place?
And where does the name “closure” come from?

They seem like separate questions, but they lead back to the same old problem: what does a variable mean, and which environment determines that meaning? Here is the thread I followed.

What is a closure?

Let’s start with a familiar definition.

A function retains access to the lexical environment where it was defined, so it can access variables from that environment even after the enclosing function has finished executing.

One detail is easy to misunderstand. A closure refers to a variable’s binding; it does not copy and store the value at the moment it is created. If the value associated with that binding changes, the value read by the closure changes too.

Why “closure”?

If the point is remembering something, why not call it memory or capture? The name instead refers to something being closed. It comes from mathematics and logic.

In the 1930s, Alonzo Church developed lambda calculus to describe computation mathematically. Variable binding is central to it.

λx. x+1

Here, x is bound by the lambda’s parameter. The following expression is different.

λx. x+y

Here, y is a free variable1. That raises a question: if a function refers to an external variable, which environment should it search?

In lambda calculus, an expression with no free variables is called a closed expression. That is the idea behind “closure”: a function that depends on external variables is combined with an environment in which those variables can be found, forming a complete unit that can be evaluated. The open expression is closed over its environment2.

A closure, then, is more than a function that remembers variables. It is a function combined with the environment on which it depends.

Closure = Function + Lexical Environment

From Lisp to Scheme: the question of environments

The question soon became a programming language problem. Lisp, designed by John McCarthy in 1958, drew on lambda calculus, but some early Lisp systems used dynamic scope.

  • Lexical scope resolves variables according to where a function is defined.
  • Dynamic scope resolves variables according to the path through which a function is called.

The difference becomes crucial when functions can be passed around and returned as values. A function may be created in one place and executed somewhere else. Handling this requires treating a function and its surrounding environment together, which is where closures become essential.

Scheme, which emerged in the 1970s, placed lexical scope and first-class functions at the center of the language. By tying a function’s meaning to its defining environment rather than its calling path, it made closures a natural part of how the language works.

A side question: has dynamic scope disappeared?

Most languages today use lexical scope by default, but the idea of dynamic scope has not disappeared. The idea that a value depends on the current execution context reappears in output streams, logging, transactions, asynchronous context, and dependency injection.

Example 1: Node.js AsyncLocalStorage
Instead of passing parameters through every call, code can read context associated with the current asynchronous execution and carry state through callbacks and Promise chains. This does not make JavaScript’s variable scope dynamic. Ordinary variables still follow lexical scope, while a separate API manages execution context.

Example 2: React Context
JavaScript itself is lexically scoped, but a React Context value depends on the nearest provider in the component tree. This resembles dynamic scope in that the surrounding usage context determines the value. It differs from traditional dynamic scope because lookup follows the component tree, rather than the function call stack.

The limits of dynamic scope
Dynamic scope has clear drawbacks. It can be hard to see which variables a function depends on just by reading its code, and changes in callers can affect unexpected places. Modern languages therefore tend to separate two concerns.

Use lexical scope to determine the meaning of ordinary variables, and a separate mechanism to pass the specific context that needs to be shared during execution.

Dynamic binding can fit information that naturally belongs to an execution context, such as the current database connection or request. The cost is that dependencies become less visible.

let belongs to this history too

JavaScript did not invent let. Mathematics has long used expressions like this:

let x = 10 in x + 1

It means “evaluate x + 1 in an environment where x is defined as 10.” Scheme uses a similar idea: create local bindings and evaluate an expression within the region where those bindings are valid. The key is explicitly limiting the scope of a variable.

Why did JavaScript’s var have function scope?

JavaScript had lexical scope and closures from the beginning. Yet var had function scope rather than block scope. A variable declared inside a block could still be accessed outside it, which confused developers coming from other languages.

A language with several lineages

When Brendan Eich designed JavaScript in 1995, it brought together features from different language families.

  • Scheme: first-class functions, lexical scope, and closures
  • Self: a prototype-based object model
  • Java/C: brace syntax and control structures such as for and if

This produced an interesting mismatch. The language looked like C or Java, with their braces, but var did not create a new scope for every block the way local declarations in those languages do. The syntax came from the C family, but the scoping behavior did not match that appearance.

Early JavaScript was designed to add small interactions to web pages. It was hard to anticipate the complex applications people would eventually build with it. Function-level scope was a comparatively simple model for that setting.

The more unusual part is hoisting

The particularly unusual behavior of var is hoisting3.

function example() {
  console.log(x); // undefined

  var x = 10;
}

A var binding exists from the start of a function and is initialized to undefined. It can therefore be accessed before its declaration statement, as though the declaration had been lifted to the top. The code is not literally moved. The bindings are prepared as part of setting up execution, before the function body runs.

Why process declarations in advance? Programming languages often separate declaring a name from computing its value. Processing function declarations ahead of time allows functions to be called before their textual declarations, makes mutual references easier, and reduces dependence on declaration order.

How let differs

A let binding remains uninitialized until its declaration executes. This interval is called the temporal dead zone, or TDZ.

function example() {
  console.log(x); // ReferenceError

  let x = 10;
}

People sometimes describe this as “let is not hoisted,” but a more accurate understanding is that the binding is created ahead of time and initialization is delayed.

To preserve backward compatibility, JavaScript standardized new declarations, let and const, in ES2015 instead of changing the meaning of var. The introduction of let was therefore more than a fix for var. It extended the language so that variable scope could align more closely with the structure of the code.

var and let through the lens of closures

Now we can return to the original question.

  • With var, multiple closures share one i binding.
  • With let in the loop declaration, each iteration gets a separate i binding.
  • In both cases, closures refer to bindings, rather than snapshots of values.

The per-iteration bindings in for (let i = ...) come from an abstract operation4 called CreatePerIterationEnvironment, defined in the ES2015 specification. It creates a new lexical environment and copies the values from the previous bindings into new ones.

A quiz: when a closure is created and when a value changes

What does this code print?

const callbacks = [];

for (let i = 0; i < 3; i++) {
  callbacks.push(() => i);
  i += 1;
}

console.log(callbacks.map(fn => fn()));

The answer is [1, 3], rather than [0, 2]. Creating a closure does not freeze the value of i. The next line, i += 1, changes the very binding that the closure refers to.

The loop’s i++ behaves differently. It executes after a new lexical environment has been created for the next iteration, so it does not change the previous iteration’s binding, which the existing closure still refers to. Both expressions change something named i, but they change bindings in different environments.

A further question: is a variable a value or an identity?

Understanding closures changed how I think about variables. I used to picture a variable as a place to store a value. Once I understood that closures refer to bindings, rather than copying values, I had to distinguish names, bindings, and values.

let x = 10;
const getX = () => x;
x = 20;

getX(); // 20

getX refers to the binding named x, rather than the value 10. The binding remains the same while its value can change.

function createCounter() {
  let count = 0;
  return () => ++count;
}

const a = createCounter();
const b = createCounter();

a(); // 1
a(); // 2
b(); // 1

Conversely, the same name, count, refers to independent bindings because each call creates a new lexical environment. The same name can refer to different bindings, and the same binding can hold different values over time.

Not every language permits this kind of change. In Clojure5, local bindings are immutable by default, and state changes are handled through separate mechanisms.

(let [x 10]
  (+ x 1))
;; 11

JavaScript makes it easy to express changing state directly through one name. Clojure makes it easier to reason about code with the assumption that a binding will not change. The two languages make different choices about state.

Should a variable name stand for one value?
Or may it refer to state that changes over time?

There does not have to be one answer. What matters is that even a familiar concept like a variable depends on the computational model a language chooses. This does not mean there is a straight line from 1930s lambda calculus to JavaScript’s let, but I can no longer see let as merely a safer declaration than var.

The biggest discovery for me was learning to separate rebinding from changes in state. In React, calling setCount does not change the count binding in the current render. The next render creates a new binding instead.

A story that begins with “where should I find this y?” reaches all the way to the let declarations and React state we use today. Even the variables we work with every day deserve another look.

  1. A free variable is used inside a function but is neither declared there nor supplied as a parameter. A closure carries the environment in which these variables can be resolved.↩
  2. Peter Landin is credited with introducing the term “closure” for this concept in the 1960s.↩
  3. To hoist means to lift or raise something.↩
  4. An abstract operation is a pseudocode algorithm defined by the specification. Like an interface, it defines rules for behavior, but it also specifies procedural steps. It does not mandate a particular implementation technique.↩
  5. The similarity between the names Clojure and closure is a play on words.↩