← ByteDance Interview Insights
I knew the var version was a classic gotcha but I still fumbled explaining the order.
First, explain the behavior with var: the loop schedules five setTimeout callbacks, each capturing the same function-scoped variable i, so after the loop i is 5 and all callbacks log 5. Then contrast with let: each iteration creates a new block-scoped binding, so the callbacks log 0,1,2,3,4 in order. Finally, mention the final console.log(i) after the loop: with var it logs 5, with let it throws a ReferenceError because i is not defined outside the block.
Pro tip: Demonstrate depth by noting that the var behavior is a classic closure-in-loop pitfall, and that let's per-iteration binding is specified in the ECMAScript spec (CreatePerIterationEnvironment), not just an implementation detail.
Explain that var is function-scoped, so all setTimeout callbacks close over the same i, which ends at 5. The callbacks run after the loop, so they all print 5.
Explain that let is block-scoped and creates a fresh binding per iteration, so each callback captures its own i value, printing 0 through 4 in order.
State that after the loop, console.log(i) prints 5 with var, but with let it throws a ReferenceError because i is not in scope outside the loop block.
Conclude the exact output: with var, five 5s then 5; with let, 0,1,2,3,4 then ReferenceError. Emphasize that setTimeout callbacks are asynchronous and run after the synchronous loop completes.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.