// Function to create a counter using closure
function createCounter() {
let count = 0;
// Closure: Inner function maintains access to the outer function's variable
return function() {
count++;
return count;
};
}
// Create a counter using the createCounter function
const counter = createCounter();
// Usage: Increment and display the counter value
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
code
JavaScript Closure for Creating a Counter
This JavaScript code defines a createCounter function that returns a closure, which is an inner function maintaining access to the outer function's count variable. When the closure is invoked through the counter variable, it increments and returns the counter value. The comments provide explanations for each part of the code.
Closure
Counter