Skip to content

OutputNot attempted

Closures read the latest value; var is hoisted

let x = 10;
function A() {
setTimeout(function () {
console.log(x);
console.log(y);
}, 0);
}
A();
x = 99;
var y = 20;

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

The timer runs after all the sync code, and closures see the variable, not a snapshot: x is 99 by then. y is a hoisted var that has been assigned 20 by the time the timer fires, so there is no TDZ issue.