JavaScript Event Loop: Sync, Async, and Micro/Macrotasks Explained

Interview question (JavaScript): “In what order do these console.logs appear—and why?” If you’ve ever been asked about the Event Loop, this is one of the most common traps: mixing sync code, async/await, Promises (microtasks) and setTimeout(0) (macrotasks). console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); (async function run() {   console.log("D");   await null;   console.log("E"); })(); console.log("F"); 🧠 Predict the output order Most people guess something like: A, B, C, D, E, F — but that’s not how JS schedules work. ✅ Correct order A → D → F → C → E → B Why that happens (step-by-step) Think of JS execution like 3 lanes: 1) Call Stack (sync runs now) - A prints immediately - the async function starts immediately → prints D - await null pauses the async function and schedules the continuation as a microtask - F prints immediately 2) Microtask Queue (high priority) — drained completely - Promise.then(...) is a microtask → prints C - the await continuation resumes → prints E 3) Macrotask Queue (task queue) — one per tick setTimeout(..., 0) runs later → prints B Visual mental model If you can explain this clearly in an interview, you’re basically demonstrating: Event loop understanding + async scheduling + debugging intuition. #JavaScript #TypeScript #Frontend #WebDevelopment #SoftwareEngineering #InterviewPrep #TechInterviews #EventLoop #AsyncAwait #Promises #ReactJS #NodeJS #EngineeringLeadership #CleanCode #ProgrammingTips

  • diagram

To view or add a comment, sign in

Explore content categories