Explain JavaScript Scope, Closures, Timers, and the Event Loop
Company: Apple
Role: Frontend Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
# Explain JavaScript Scope, Closures, Timers, and the Event Loop
Answer the following JavaScript runtime questions precisely. Distinguish the language execution model from browser-provided APIs.
### Clarifying Questions to Ask
- Are we discussing JavaScript in a browser, Node.js, or the language specification alone?
- Is the code executed as a classic script or an ECMAScript module?
- May the answer assume a modern standards-compliant browser?
### Part 1: Event Loop and Execution Order
Is JavaScript single-threaded or multi-threaded? Explain call-stack execution, host APIs, task queues, microtasks, and whether source code simply runs "top to bottom."
#### What This Part Should Cover
- One JavaScript call stack per ordinary execution context
- Concurrency supplied by the host environment
- Run-to-completion and microtask-versus-task ordering
### Part 2: Scope, Closures, and the Timer Loop
State the output of this code and explain it:
```javascript
for (var i = 0; i < 10; i++) {
setTimeout(() => console.log(i), 0);
}
```
Then explain how `let`, closures, and the temporal dead zone change the reasoning.
#### What This Part Should Cover
- Function scope for `var` and one shared binding
- A fresh per-iteration binding for `let`
- Lexical capture by closures
- Declaration, initialization, and temporal-dead-zone errors
### Part 3: Timers and Deferred Scripts
Compare `setTimeout` with `setInterval`. Explain what the HTML `defer` attribute does and whether it applies to an `img` element.
#### What This Part Should Cover
- Minimum-delay rather than exact-time semantics
- Interval drift and overlapping work concerns
- Deferred classic-script download and ordered execution after parsing
- `defer` not being an image-loading control
### What a Strong Answer Covers
- Exact output plus the queueing and scope explanation behind it
- Clear separation of JavaScript, browser APIs, and worker threads
- Practical consequences for responsiveness and timer scheduling
- Correct terminology without claiming that all JavaScript everywhere has one global thread
### Follow-up Questions
- Where do promise callbacks run relative to zero-delay timers?
- How can the loop be fixed without changing `var` to `let`?
- Why can `setInterval` be a poor choice for an async polling request?
- How do `async` and `defer` differ on script elements?
Quick Answer: Explain JavaScript execution order through scope, closures, host APIs, the event loop, task queues, and microtasks. The interview also examines var versus let in timer callbacks, temporal dead zones, timeout and interval behavior, and the precise role of the HTML defer attribute.