Skip to the workspace
Pebellslearn by building
Functions  ›  Lesson

Closures

Closures 12 min

javascript / Closures

Explore each scene at your own pace.

01 · Closures

Closures

Closures

A closure is a function together with access to its surrounding lexical environment. It can retain access to bindings after the outer call returns.

The remembered binding can keep changing; a closure is not a frozen photograph of its first value.

See the mechanism

Walk through the modelClosuresAuthored snapshots of the example; use Run below to test the code.
counter A retains count0
The returned function keeps access to this invocation’s binding.
1 of 3

Follow one example

javascript

The first two calls use the same retained count binding, producing 1 then 2. Calling makeCounter again creates an independent binding starting at 0, so its first increment produces 1. The outer invocation returns, but the returned function still has access to the binding it uses.

Predict, change and check

Predict: If you call makeCounter inside every iteration, will one counter keep increasing?

Test your explanation: Create two counters and alternate their calls. Write a separate count box for each outer invocation to explain why neither changes the other.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

A closure retains bindings, not frozen screenshots

A closure is a function together with access to its lexical environment. A later call can observe a retained binding's updated value. Creating two independent counter factories can create two independent environments; calling the same returned counter twice reuses one environment.

Captured values can retain large objects or detached DOM nodes through an ownership path. A closure is useful, not automatically a leak; the question is whether something keeps it reachable longer than intended. Test separate instances and shared instances, then explicitly release owners during component cleanup.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.