← ByteDance Interview Insights

ByteDance·Frontend Engineer·Technical Phone Screen·Intermediate

Intermediate
Apr 2026

Summary

A frontend phone screen at Bytedance that zeroed in on JavaScript closure mechanics. One question, but they really wanted you to dig into it.

Questions Asked (1)

Q1

Given a for loop that uses setTimeout to log the loop counter, predict the output and explain why it behaves differently with var versus let. Walk through how the event loop interacts with closures here, and describe at least one way to fix the var version.

Technical Trade-offsAlgorithms & Data Structures
Author's notes

This is one of those questions where you either know it cold or you fumble the explanation even if you know the answer.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

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.

1. Predict the output

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.

2. Explain var behavior

Explain that var is function-scoped, so all closures share the same variable, which by the time callbacks execute has the final value.

3. Explain let behavior

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.

4. Describe event loop interaction

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.

5. Provide a fix for var

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.

Key Points to Mention

  • var is function-scoped, let is block-scoped
  • Closures capture variables by reference, not value
  • The event loop executes synchronous code first, then asynchronous callbacks
  • setTimeout callbacks are macrotasks and run after the current execution context
  • IIFE creates a new scope for each iteration
  • Using let in for loops creates a new binding per iteration

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.