CodePark/ questions / Closures
START PRACTICINGPRACTICE
Frontend question · JavaScript › Closures

What does this log?

let x = 1;
function makeLogger() {
  return () => console.log(x);
}
const log = makeLogger();
x = 2;
log();
2

A closure holds a live link to the variable, not a snapshot of its value when the closure was created. When log() runs, x has already been changed to 2, so it logs 2.

The tempting option "1" is wrong because it assumes the closure copied
x when makeLogger() was called. It did not.