Sobes.tech
Junior — Middle

Can you give an example of when a closure is used in JavaScript to store data or create private methods?

sobes.tech AI

Answer from AI

In JavaScript, closures are often used to create private data and methods that are inaccessible from outside.

Example:

function Counter() {
  let count = 0; // private variable

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

const counter = Counter();
console.log(counter.increment()); // 1
console.log(counter.getCount());  // 1
console.log(counter.count);       // undefined — cannot access count from outside

Here, count is stored in the closure of the Counter function and is not directly accessible, which ensures data encapsulation.

Can you give an example of when a closure is used in… - sobes.tech