JavaScript Closures
What is a Closure?
Section titled “What is a Closure?”A closure is a function that retains access to variables from its outer scope, even after the outer function has finished executing.
Basic Example
Section titled “Basic Example”function createCounter() { let count = 0;
return { increment() { count++; return count; }, getCount() { return count; } };}
const counter = createCounter();console.log(counter.increment()); // 1console.log(counter.increment()); // 2console.log(counter.getCount()); // 2Why Closures Matter
Section titled “Why Closures Matter”- Data privacy - Create private variables
- Function factories - Generate functions with different configurations
- Event handlers - Retain references to data when handling events
- Callbacks - Pass context into async operations
Gotchas
Section titled “Gotchas”- Closures hold a reference to the variable, not the value at creation time
- Be careful with closures in loops - use
letinstead ofvar - Memory leaks can occur if closures hold references to large objects unnecessarily