A closure happens when a function remembers variables from its outer function/scope even after the outer function has finished executing.
Example:
function counter() {
let count = 0; // local variable
return function () { // inner function
count++; // still accessing the outer variable
console.log(count);
};
}
let c = counter(); // counter() is done executing now
c(); // 1
c(); // 2
c(); // 3
Why does c() still increment count when counter() has already finished?
Because the inner function kept a reference to the variable count.
That preserved scope = closure.
Top comments (0)