Skip to content
Closures
step 1/7

Reading — step 1 of 7

Learn

~3 min readScope and Closures

A closure is a function that remembers the variables of the scope where it was created — even after that scope has finished executing. Closures are the engine behind callbacks, partial application, private state, and module patterns. Understanding them deeply is the line between intermediate and senior JavaScript.

The mental model

js

When makeAdder(5) runs, it returns the inner function. Normally, x would disappear when makeAdder returned — but the inner function still references x. So JavaScript keeps x alive for as long as any function still needs it.

add5 and add10 are different closures — each has its own captured x. They don't share state.

Why closures are everywhere in JavaScript

Every callback you've written is a closure. Every event handler, every setTimeout, every array method callback. They all capture variables from the surrounding scope:

js

Building private state

Closures let you simulate private members — without classes:

js

Nothing outside createCounter can read or write count directly. The only access is through the returned methods. This was THE pattern for encapsulation before ES6 classes.

⚠️ The classic loop-closure trap

js

Why? var is function-scoped, so all three closures share the SAME i. By the time the timeouts fire, the loop is done and i === 3.

Fix #1: use let (block-scoped — each iteration gets its own i):

js

Fix #2 (older code): wrap in an IIFE to create a new scope:

js

Switching to let makes this footgun mostly history, but you'll see the bug in legacy code.

Closures and memory

Closures keep their captured variables alive — even when the outer function is long gone. Be careful with closures that capture LARGE values you no longer need:

js

If you only need a small piece, capture just that piece:

js

Common mistakes

  • Loop with var — all closures share the same variable. Use let.
  • Returning a closure that captures large objects — keeps them in memory.
  • Confusing closure with this — closures capture variables; this is bound by call site (next lesson on this).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Closures — JavaScript Intermediate