# JavaScript (ES6+) Runtime: Event Loop (Microtasks vs Macrotasks), Closures, Hoisting & Coercion
Exam: UGC NET Computer Science & Applications (Code 87) (UGC NET CS)
Subject: Unit 3: Programming in C, C++, Java, JavaScript & Assembly
Canonical URL: https://gateandnet.com/exams/ugc-net-cs/programming-languages/javascript-event-loop-closures-hoisting-and-prototypes

> 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`

| 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 own `this` or `arguments`** — they lexically capture `this` from their enclosing scope (so `.call()` / `.bind()` cannot override an arrow function’s `this`!).

> [!TRAP]
> **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)!

## Solved Practice Questions & PYQs

### [UGC NET CS Dec 2023 JS | MCQ]
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");`?
**Correct Answer:** C
**Solution:** Synchronous call stack logs `A` and `D` first; then the Event Loop drains **Microtasks** (`Promise.then` $\to$ `C`) *before* executing the next **Macrotask** (`setTimeout` $\to$ `B`) $\implies$ **`A, D, C, B`**.

### [UGC NET CS Web Tech | MCQ]
In JavaScript, what does `[typeof null, typeof NaN, NaN === NaN]` evaluate to?
**Correct Answer:** B
**Solution:** By ECMAScript specification: `typeof null === "object"`, `typeof NaN === "number"` (IEEE-754 float value), and `NaN === NaN` is **`false`**!
