JSVerse
Core JavaScript / Closures

Closures

A function remembers the scope it was born in, even after that scope's function has returned.

When a function is defined inside another function, it keeps a live reference to its outer function's variables — not a copy, a reference. Normally, a function's local variables disappear once it returns. But if an inner function that references them escapes (by being returned, or stored somewhere), JavaScript keeps that outer variable environment alive for as long as the inner function exists. That preserved environment is the closure. It's how `counter()` below can hand back a function that keeps incrementing the *same* `count`, instead of resetting it every time.

Codeeditable — Run executes your edits
Loading...
Console
Output will appear here
Visualization
Closure Environment
Call the outer function to create a closure
Why?

increment() closes over count by reference, not by value. Every call reuses and mutates the exact same count binding that lived inside the one counter() call that created it.