Closures allow you to maintain state across multiple function calls:
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
},
getValue: function() {
return count;
}
};
}
const counterObj = createCounter();
console.log(counterObj.increment()); // Output: 1
console.log(counterObj.increment()); // Output: 2
console.log(counterObj.decrement()); // Output: 1
console.log(counterObj.getValue()); // Output: 1