A closure is a function that has access to variables from its outer (enclosing) scope, even after the outer function has returned. They're useful for data privacy, state management, and creating function factories.
A closure is created when a function is defined inside another function, and the inner function references variables from the outer function's scope.
How Closures Work:
Common Use Cases:
function createCounter() {
let count = 0; // Private variable
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
// count is not accessible directly
console.log(count); // ReferenceError