← Lessons

quiz vs the machine

Silver1080

Frontend

Closures and Scope

A function remembers the variables of the place it was born, not the place it is called.

4 min read · intro · beat Silver to climb

Scope at creation time

JavaScript uses lexical scope, meaning where a function is written decides which variables it can see. A closure is the bundle of a function plus the variable environment it captured when it was defined.

  • Inner functions read and write the outer variables they reference.
  • Those variables stay alive as long as the closure does.
  • Each call to an outer function creates a fresh environment.

Why closures matter

Closures let you build private state without classes. The captured variables cannot be touched from outside, only through the functions you return.

  • A counter can hold a private count that only its methods change.
  • Event handlers remember the data they were set up with.
  • A common bug is capturing a loop variable that changes before the callback runs.

Using let in a loop creates a new binding each iteration, which fixes the classic closure in a loop trap that var causes. Closures are not magic, just scope that outlives the call that made it.

Key idea

A closure captures variables by reference from where it was defined, keeping that environment alive after the outer call returns.

Check yourself

Answer to earn rating on the learn ladder.

1. What determines which variables a closure can access?

2. Why does using let in a loop fix the classic closure bug?