Closure
Practical Example (Counter):
function createCounter() {
let count = 0; // Variable in the outer function
return function () {
count++; // Inner function has access to 'count'
return count;
};
}
const counter = createCounter(); // Create a closure
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
console.log(counter()); // Output: 3
Here:
createCounterdefines a privatecountvariable.- The returned function (a closure) remembers
countand updates it each time it's called, even thoughcreateCounterhas finished running.