← ByteDance Interview Insights
This is one of those questions where you either know it cold or you fumble the explanation even if you know the answer.
Start by predicting the output for both var and let versions, then explain the difference using scope and closures. Walk through the event loop's role in scheduling the setTimeout callbacks and how each version captures the loop variable. Finally, describe at least one fix for the var version, such as using an IIFE or bind.
Pro tip: Mention that this is a common pitfall in interviews and that understanding it demonstrates deep knowledge of JavaScript's execution model. Also, note that using let in loops creates a new binding per iteration, which is the modern solution.
State that with var, the output is five 5's (or the final value), while with let, it's 0,1,2,3,4. Clarify that setTimeout callbacks run after the loop completes.
Explain that var is function-scoped, so all closures share the same variable, which by the time callbacks execute has the final value.
Explain that let is block-scoped, and in a for loop, a new binding is created for each iteration, so each closure captures a different variable.
Describe how the event loop processes the call stack first, then the task queue (or microtask queue). The setTimeout callbacks are macrotasks, so they run after the synchronous loop finishes.
Offer at least one fix: wrap setTimeout in an IIFE to create a new scope, or use .bind() to pass the current value, or use a separate function to capture the value.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.