Question 43

Question

How would you create a private method using closures?

Answer

Closures are fantastic for achieving "private" methods in JavaScript.

Here's how to do it:

function Counter() {
  let count = 0; // Private variable accessible only within the closure

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

const myCounter = Counter(); 
console.log(myCounter.getCount()); // Output: 0
myCounter.increment();
console.log(myCounter.getCount()); // Output: 1

Explanation:

  1. The Outer Function (Factory): Counter() acts like a factory, creating and returning a new counter object. Inside it:

    • We declare count as our private variable. It's only visible within the scope of the Counter function.

  2. Return Object: The Counter function returns an object containing methods (increment and getCount).

  3. Closure Magic: Each method (increment, getCount) is a closure. They "remember" the count variable from their surrounding scope (the Counter function). Even after Counter() finishes executing, these methods still have access to count.

Why This Works:

  • When you call myCounter.increment(), the increment method remembers its count and increments it.

  • Similarly, when you call myCounter.getCount(), the getCount method can read the value of count.

Last updated