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

Does a JavaScript closure capture the value or the variable?

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

JavaScript
let x = 1;
const getX = () => x;
x = 2;
console.log(getX());
Show answer and explanation

The answer is 2.

A closure keeps a live reference to the variable, not a snapshot of its value. By the time getX() runs, x is 2.

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. How do closures create private variables in JavaScript?

Related topics