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

How can I use closures to create private variables in JavaScript?

Asked on Oct 07, 2025

Answer

Closures in JavaScript allow you to create private variables by defining a function within another function, where the inner function has access to the outer function's scope. This technique is often used to encapsulate data and restrict access from the outside.
<!-- BEGIN COPY / PASTE -->
        function createCounter() {
            let count = 0; // Private variable

            return {
                increment: function() {
                    count++;
                    return count;
                },
                decrement: function() {
                    count--;
                    return count;
                },
                getCount: function() {
                    return count;
                }
            };
        }

        const counter = createCounter();
        console.log(counter.increment()); // 1
        console.log(counter.increment()); // 2
        console.log(counter.decrement()); // 1
        console.log(counter.getCount());  // 1
        <!-- END COPY / PASTE -->
Additional Comment:
  • The "createCounter" function defines a private variable "count" that is not accessible directly from outside.
  • The returned object contains methods that form closures over the "count" variable, allowing controlled access and modification.
  • Each call to "createCounter" creates a new closure with its own private "count" variable.
  • This pattern is useful for encapsulating state and behavior in a controlled manner.
✅ Answered with JavaScript best practices.
← Back to All Questions