DeveloperBreeze

Counter Development Tutorials, Guides & Insights

Unlock 1+ expert-curated counter tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your counter skills on DeveloperBreeze.

JavaScript Closure for Creating a Counter

Code January 26, 2024
javascript

// 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