Frontend Interview Questions

JavaScript Closures and Scope Chain

What is a closure? Explain the classic loop-with-setTimeout bug.

Why Interviewers Ask This

Closure literacy separates people who use JS from people who understand it. Every JS interview has some form of this.

How to Answer

  1. 1

    Closure: a function plus the lexical environment it was created in. It "closes over" variables from that environment.

  2. 2

    Scope chain: when resolving a name, JS walks from innermost scope outward through the chain of lexical environments.

  3. 3

    Classic bug: `for (var i=0; i<3; i++) setTimeout(()=>console.log(i))` logs 3,3,3 — var is function-scoped, all callbacks share the same i.

  4. 4

    Fix: use let (block-scoped, fresh binding per iteration) or IIFE to capture the current value.

  5. 5

    Memory: closures hold references; if a closure outlives its scope, captured variables can't be GC'd. Common leak source.

Sample Answer

A closure is a function paired with the scope where it was born — it keeps access to those variables even after the outer function returns. The classic test: var-based for loop setting setTimeout callbacks. Because var is function-scoped, all three callbacks reference the same i, which is 3 by the time they run — so 3,3,3. Swap for let and each iteration gets its own binding, so you get 0,1,2. I use this pattern intentionally when I need data privacy — expose only methods that close over private state instead of attaching to an object. The memory footnote: a DOM node held inside a closure that outlives the node is a classic leak, easy to create with addEventListener.

Pro Tips

  • ES6 modules give you privacy for free — closures for privacy are less needed today but still show up in libraries.

  • Chrome DevTools → Memory → Heap snapshot shows closures as their own category — invaluable for leak hunting.

  • HireMe AI (即答侠) curates the top-5 closure gotchas so you recognize them by shape during interviews.

Frequently Asked Questions

Is every function a closure?

Technically yes — every function captures its lexical environment. In practice we call it a "closure" only when that capture matters, i.e., the outer scope has gone away.

Closures in arrow vs regular functions?

Same scope semantics. The difference is `this` binding (arrow inherits, regular has its own) and arguments/new.target availability.

Worried About Going Blank in Your Interview?

HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.

Try HireMe AI Free