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

How does a closure counter work in JavaScript?

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

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

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

The answer is 3.

The arrow function is a closure: it keeps a reference to count even after counter() has returned. Every call increments the same variable.

Take the full quiz Next question →

More Closures questions

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

Related topics