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

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

Asked on Oct 06, 2025

Answer

Closures in JavaScript allow you to create private variables by enclosing them within a function scope, making them inaccessible from outside that function. Here's a simple example demonstrating this concept.
<!-- 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.
  • This pattern is useful for encapsulating data and restricting direct access, promoting data integrity.
✅ Answered with JavaScript best practices.
← Back to All Questions