How JavaScript Executes Your Code: The Event Loop

💡 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 — 𝗧𝗵𝗲 𝗥𝗲𝗮𝘀𝗼𝗻 𝗬𝗼𝘂𝗿 𝗖𝗼𝗱𝗲 𝗗𝗼𝗲𝘀𝗻’𝘁 𝗥𝘂𝗻 𝗶𝗻 𝗢𝗿𝗱𝗲𝗿⚙️ Most developers know about the Event Loop, but few truly understand how JavaScript executes your code step by step — from the Global Execution Context to Web APIs, Task Queues, and Microtasks 🌀 Let’s break it down like a system engineer 👇 🧠 𝗛𝗼𝘄 𝗶𝘁 𝗦𝘁𝗮𝗿𝘁𝘀 — 𝗧𝗵𝗲 𝗚𝗹𝗼𝗯𝗮𝗹 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗖𝗼𝗻𝘁𝗲𝘅𝘁 When JavaScript runs, it first creates a Global Execution Context (GEC) — this contains: -> the Memory Component (variables, functions) -> the Code Component (thread of execution) It’s stored in the Call Stack, which works on a simple principle — LIFO (Last In, First Out). ⚙️ 𝗪𝗵𝗮𝘁 𝗛𝗮𝗽𝗽𝗲𝗻𝘀 𝗪𝗵𝗲𝗻 𝗬𝗼𝘂 𝗖𝗮𝗹𝗹 𝗮 𝗧𝗶𝗺𝗲𝗿 𝗼𝗿 𝗔𝗣𝗜 The browser (or Node.js) provides Web APIs like: -> setTimeout -> fetch -> DOM events These are not part of JS itself — they are handled by the environment. Once completed, their callbacks move to the Task Queues. 🧩 𝗧𝘆𝗽𝗲𝘀 𝗼𝗳 𝗧𝗮𝘀𝗸 𝗤𝘂𝗲𝘂𝗲𝘀 1️⃣ Macrotask Queue (Task Queue): Contains → setTimeout, setInterval, setImmediate, fetch callbacks, and DOM events. 2️⃣ Microtask Queue: Contains → Promise.then, async/await, and process.nextTick (Node.js). ⚡ 𝗧𝗵𝗲 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 — 𝗧𝗵𝗲 𝗕𝗿𝗮𝗶𝗻 𝗼𝗳 𝗜𝘁 𝗔𝗹𝗹 After every macrotask, the Event Loop checks the Microtask Queue — and executes all microtasks before picking up the next macrotask. Why? Because microtasks are usually short, immediate reactions (like resolved Promises) and must run before the next rendering or I/O task. 🧩 𝗤𝘂𝗶𝗰𝗸 𝗗𝗲𝗺𝗼 console.log("Start"); setTimeout(() => console.log("Macrotask"), 0); Promise.resolve().then(() => console.log("Microtask")); console.log("End"); 📤 Output: Start End Microtask Macrotask ✅ The Microtask Queue (Promise) runs before Macrotask Queue (setTimeout). 💭 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: JavaScript is single-threaded, but not blocking — thanks to the event loop and task queues managing concurrency intelligently⚙️ Understanding this flow separates coders from engineers. #JavaScript #EventLoop #FrontendDevelopment #AsyncProgramming #WebDevelopment #FrontendEngineer #100DaysOfCode #SoftwareEngineering #TechLearning #Coding

  • diagram

I’ve read about the event loop many times, but demos like this help it click better.

To view or add a comment, sign in

Explore content categories