JS Trap
JavaScript Event Loop: Why a Promise Runs Before setTimeout 0
· JavaScript event loop: setTimeout 0 vs Promise | kaun pehle chalega?
Predict the output: log A, a 0 ms setTimeout logs B, Promise.then logs C, log D. Node prints A D C B. Sync code runs first, then the event loop drains every microtask (promises) before the next task (timers). A classic JavaScript interview question.
The code
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");![Animated JavaScript comparisons: 0 == "0" is true, 0 == [] is true and "0" == [] is false, then a conversion lane turns [] into an empty string and then 0, ending on ===.](https://i.ytimg.com/vi/aXBolMH19gs/maxresdefault.jpg)


![Animated sliding window over the array [2, 1, 5, 1, 3, 2]: a three-number window adds the new number and subtracts the old one, showing sums 8, 7, 9 and 6 and a maximum of 9.](https://i.ytimg.com/vi/NM5paB6_7wg/maxresdefault.jpg)