Function Closures in JavaScript
? Function Closures in JavaScript
What is a Closure?
A closure is a function that remembers and accesses variables from its lexical scope even when that outer function has finished executing.
It “closes over” variables from its surrounding context.
Why are Closures Useful?
To encapsulate private variables.
To maintain state between function calls.
To create factory functions and callbacks with preserved data.
How Closures Work: Basic Example
function outer() { let count = 0; // variable in outer scope function inner() { count++; // accesses and updates outer variable console.log(count); } return inner;}const counter = outer();counter(); // Output: 1counter(); // Output: 2counter(); // Output: 3inner()forms a closure that keeps thecountvariable alive even afterouter()returns.
Another Example: Private Variables
function makeCounter() { let count = 0; return { increment: function() { count++; return count; }, decrement: function() { count--; return count; } };}const counter = makeCounter();console.log(counter.increment()); // 1console.log(counter.increment()); // 2console.log(counter.decrement()); // 1The variable
countis private and can only be accessed/modified via the returned methods.
Important Notes
Closures capture variables, not their values. So if the variable changes, closures see the updated value.
Beware of common pitfalls with closures in loops (use
letinstead ofvar).
Summary
| Aspect | Description |
|---|---|
| Closure | Function + preserved outer scope |
| Useful for | Data privacy, stateful functions |
| Keeps variables alive | Even after outer function ends |
Want me to explain common closure pitfalls or how closures power module patterns?