easypredictionjavascript~5 min
Predict the Closure Output
Objective: Explain why `var` shares one binding across iterations while `let` creates a fresh binding per iteration.
Two loops push functions that log a loop variable. Predict everything printed when both lists run.
- Write one line per console.log, in the order they print.
- Write values only, without quotes.
Read the code, then type what it prints
var fns = [];
for (var i = 0; i < 3; i++) {
fns.push(function () { console.log(i); });
}
fns.forEach(function (fn) { fn(); });
var gs = [];
for (let j = 0; j < 3; j++) {
gs.push(() => console.log(j));
}
gs.forEach((fn) => fn());Output
> Nothing has run yet.
Interview follow-up questions
- How would you fix the first loop without using `let`?
- What does the spec say about per-iteration bindings in for-loops?
- Where have closures over loop variables caused bugs in event handlers you've written?