234
Top Answer
A closure is a function that remembers the variables from its outer scope even after the outer function has finished executing.
Simple Example
function createCounter() {
let count = 0; // This variable is "enclosed"
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
The inner function "closes over" the count variable and keeps it alive.
Practical Use Cases
- Data privacy - Variables can't be accessed directly from outside
- Function factories - Create specialized functions
- Event handlers - Preserve state between events
- Partial application - Pre-fill some arguments
JSTeacher