JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network
Q&A Logo

How do closures work in JavaScript, and why are they useful for managing state in functions? Pending Review

Asked on Oct 12, 2025

Answer

Closures in JavaScript allow a function to access variables from its outer scope even after the outer function has finished executing. They are useful for managing state because they enable private variables and encapsulation.
<!-- BEGIN COPY / PASTE -->
        function createCounter() {
            let count = 0;
            return function() {
                count += 1;
                return count;
            };
        }

        const counter = createCounter();
        console.log(counter()); // 1
        console.log(counter()); // 2
        console.log(counter()); // 3
        <!-- END COPY / PASTE -->
Additional Comment:
  • The "createCounter" function returns an inner function that has access to the "count" variable.
  • Each call to "counter()" increments and returns the "count" value, demonstrating how closures maintain state.
  • Closures are beneficial for data encapsulation, as the "count" variable is not directly accessible from outside the "createCounter" function.
✅ Answered with JavaScript best practices.
← Back to All Questions