A closure is a fundamental JavaScript concept where a function retains access to variables from its outer scope even after the outer function has finished executing. In simpler terms, it's like a function remembering the environment it was created in.
function createCounter() {
let count = 0; // This variable is "enclosed" in the closure
return {
increment: function() {
count++;
return count;
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.getCount()); // Output: 0
console.log(counter.increment()); // Output: 1
console.log(counter.increment()); // Output: 2
Closures are commonly used in: