∑GateAndNet
PlannerSign Up
INTERMEDIATECore Topic 4 min read 5 views

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

javascript
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

Featurevarletconst
ScopeFunction-scopedBlock-scoped { ... }Block-scoped { ... }
HoistingHoisted & initialized to undefinedHoisted 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 own this or arguments — they lexically capture this from their enclosing scope (so .call() / .bind() cannot override an arrow function’s this!).
Common Exam Mistake

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)!

Key Formulas Summary
JavaScript Event Loop Turn Execution Priority
1. Sync Call Stack  ⟶  2. Drain ALL Microtasks (Promise.then)  ⟶  3. ONE Macrotask (setTimeout)\text{1. Sync Call Stack} \;\longrightarrow\; \text{2. Drain ALL Microtasks (}\texttt{Promise.then}\text{)} \;\longrightarrow\; \text{3. ONE Macrotask (}\texttt{setTimeout}\text{)}
Note: Even setTimeout(fn, 0) runs AFTER all pending Promise microtasks finish!
#JavaScript#Event Loop#Promises#Closures#Hoisting#Prototypes#Web Tech#UGC NET CS

Practice Questions on This Chapter (2)

Q1UGC NET CS Dec 2023 JSMCQMEDIUM
+2M • 0 Neg

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");?

⚡ Click an option above to verify instantly
Q2UGC NET CS Web TechMCQEASY
+2M • 0 Neg

In JavaScript, what does [typeof null, typeof NaN, NaN === NaN] evaluate to?

⚡ Click an option above to verify instantly
Previous TopicJava & JVM Architecture: String Pool, Integer Cache, Interfaces, Exceptions & ConcurrencyNext Topic Assembly Languages (8085, 8086 & RISC): Registers, Flags, T-States, Interrupts & Traces