Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

How do closures create private variables in JavaScript?

Do you know what will be the output of this code?

JavaScript
const counter = (function () {
  let count = 0;
  return { inc: () => ++count };
})();

counter.inc();
console.log(counter.count);
Show answer and explanation

The answer is undefined.

count is a local variable of the immediately invoked function, not a property of the returned object. Only inc can reach it through its closure. That’s the module pattern for private state.

Take the full quiz Next question →

More Closures questions

  1. How does a closure counter work in JavaScript?
  2. Why does var in a loop with setTimeout print 3 3 3?
  3. Why does let in a for loop fix the setTimeout closure problem?
  4. Do two closures from the same function share state?
  5. Does a JavaScript closure capture the value or the variable?

Related topics