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

Do two closures from the same function share state?

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

JavaScript
function make() {
  let n = 0;
  return () => ++n;
}

const a = make();
const b = make();
a();
a();
console.log(b());
Show answer and explanation

The answer is 1.

Every call to make() creates a new n. a and b close over different variables, so calling a twice doesn’t affect b.

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. Does a JavaScript closure capture the value or the variable?
  5. How do closures create private variables in JavaScript?

Related topics