function counter() {
let count = 0;
return function() {
count++;
console.log(count);
};
}
const increment = counter();
increment(); // Output: 1
increment(); // Output: 2
increment(); // Output: 3
In this example, the count
variable is private to the counter
function. The only way to manipulate count
is through the returned function, which forms a closure over the count
variable.