Published on January 26, 2024By DeveloperBreeze
// 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
Comments
Please log in to leave a comment.