JavaScript Output Prediction Hard +35 XP
Closure Trap
What does this log?
JavaScriptRead-only
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// Output after all timeouts:What is the output?
Show answer and explanation
Answer: 3 3 3
var is function-scoped. By the time setTimeout fires, the loop has ended and i is 3. Use let to fix this.
Hint: var does not create block scope.
What this challenge tests
Output Prediction in JavaScript: closures, async, var-vs-let.