Closure Visualizer
Each counter remembers the multiplier from when it was created — that's a closure.
No closures yet
Press + createCounter() above. Each closure gets its own private count and remembers the multiplier from when it was born.
How Closures Work
A straightforward technical explanation of closures.
- 📚A function retains access to the lexical scope in which it was declared.
- 🔒Variables are captured within the scope, retaining their state at the time of creation.
- 🛡️Each closure maintains its own isolated environment, preventing external access to internal variables.
- ♻️Once a closure is no longer referenced, the memory it occupies is garbage collected.
Lexical Scoping in Action
In JavaScript, functions form closures. A closure is the combination of a function bundled together with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
When a function is created inside another function, it maintains a reference to its lexical environment. This allows the inner function to access variables declared in the outer function, even after the outer function has finished executing.
Demonstrating State Retention
When you create a counter with multiplier = 5, the newly returned function retains access to its specific multiplier value. Modifying the global multiplier variable subsequently only affects future counters.
If you instantiate a second counter with multiplier = 1, it operates completely independently. Each instance of the outer function execution creates a new lexical environment, meaning the internal variables like count and the captured multiplier are unique to each closure.
Practical Applications
Closures are fundamental for data encapsulation and privacy. By returning a function that accesses an internal variable like count, you prevent the external scope from directly reading or modifying that data.
They are heavily utilized in asynchronous programming, event handlers, and functional programming patterns. In frameworks like React, closures are essential for components to capture their state and props during a specific render cycle.
Want to dive deeper?
Read exactly how they work step-by-step in my practical guide:
What is JavaScript Closures? A Practical Guide