JavaScript (ES6+) Runtime: Event Loop (Microtasks vs Macrotasks), Closures, Hoisting & Coercion
Single-threaded JS Call Stack, Microtask Queue (Promise/queueMicrotask/async-await) priority over Macrotask Queue (setTimeout), var hoisting vs let/const TDZ, prototypal chain, and == coercion.
1. Event Loop Output Tracing: Synchronous vs Microtasks vs Macrotasks
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => {
console.log("3");
Promise.resolve().then(() => console.log("4"));
});
console.log("5");
// Exact Output: 1, 5, 3, 4, 2
Why? Synchronous code logs 1 and 5 first. Before picking the setTimeout macrotask (2), the Event Loop completely drains the Microtask Queue, including newly enqueued microtasks (3 then 4)!
2. var vs let / const, Temporal Dead Zone (TDZ) & this
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped { ... } | Block-scoped { ... } |
| Hoisting | Hoisted & initialized to undefined | Hoisted into TDZ (ReferenceError before line) | Hoisted into TDZ |
Loop Closure for (.. i < 3) | Shares 1 binding (prints 3, 3, 3) | Fresh binding per iteration (0, 1, 2) | Cannot increment |
- Arrow Functions
() => {}vs Regular Functions: Arrow functions have NO ownthisorarguments— they lexically capturethisfrom their enclosing scope (so.call()/.bind()cannot override an arrow function’sthis!).
Famous JS Type Quirks: typeof null === "object" (legacy 1995 tag bug), typeof NaN === "number", NaN === NaN is false (use Number.isNaN()), "5" + 3 === "53" (string concat), whereas "5" - 3 === 2 (numeric coercion)!
Practice Questions on This Chapter (2)
In JavaScript (ES6+), in what exact order are characters logged by: console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D");?
In JavaScript, what does [typeof null, typeof NaN, NaN === NaN] evaluate to?