← ByteDance Interview Insights

ByteDance·Frontend Engineer·Technical Phone Screen·Intermediate

Intermediate
Jun 2026

Summary

Bytedance frontend screen, pretty much one meaty JavaScript question that spiraled into a full conversation about scoping and the event loop. Not a bad experience but you better actually know how closures work.

Questions Asked (1)

Q1

What does this loop print, and in what order? A for loop runs five times using var, scheduling a setTimeout callback each iteration, then logs i after the loop. What changes if you swap var for let?

Technical Trade-offsAlgorithms & Data Structures
Author's notes

I knew the var version was a classic gotcha but I still fumbled explaining the order.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

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.

1. Analyze var behavior

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.

2. Analyze let behavior

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.

3. Address the final console.log

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.

4. Summarize output order

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.

Key Points to Mention

  • var is function-scoped; let is block-scoped
  • Closures capture variables by reference, not value
  • setTimeout callbacks are asynchronous and execute after the loop
  • let creates a new binding per iteration (per-iteration environment)
  • The final console.log(i) after the loop: 5 with var, ReferenceError with let
  • Output order: with var, five 5s then 5; with let, 0,1,2,3,4 then ReferenceError

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