Closures, A Primer
What is a Closure?
function createGreeter(greeting) {
// The inner function is a closure that "captures" the greeting variable
return function(name) {
return `${greeting}, ${name}!`;
};
}
// Create closures with different captured values
const sayHello = createGreeter("Hello");
const sayHi = createGreeter("Hi");
// Use the closures
console.log(sayHello("Alice")); // "Hello, Alice!"
console.log(sayHi("Bob")); // "Hi, Bob!"How Closures Work
Lexical Scope
Execution Context and Environment
Memory Management and Garbage Collection
Practical Uses of Closures
1. Data Encapsulation and Privacy
2. Function Factories
3. Maintaining State in Async Operations
4. Event Handlers with Preset Data
Closures in Happen's Event Continuum
Best Practices for Closures
Last updated