🔄 JavaScript is single-threaded. So how does it handle multiple tasks at once? Meet the Event Loop. It's the unsung hero that keeps your browser from freezing while waiting for an API call. Many developers use setTimeout or fetch daily without knowing what happens under the hood. Here is the architecture that makes non-blocking I/O possible: 1️⃣ Call Stack (The Boss): JavaScript does one thing at a time. It executes functions LIFO (Last In, First Out). If the stack is busy, nothing else happens. 2️⃣ Web APIs (The Assistants): When you call setTimeout or fetch, the browser takes that task out of the Call Stack and handles it in the background (Web APIs). This frees up the stack to keep running your code! 3️⃣ Callback Queue (The Waiting Room): Once the background task is done (e.g., the timer finishes), the callback function is moved to the Queue. It waits there patiently. 4️⃣ The Event Loop (The Traffic Controller): This is the infinite loop. It constantly checks: - "Is the Call Stack empty?" - "Is there something in the Queue?" - If Stack is Empty AND Queue has items 👉 Move item to Stack. Understanding this flow is the key to debugging weird async behavior. Did you know setTimeout(fn, 0) is a hack to defer execution until the stack is clear? #JavaScript #WebDevelopment #EventLoop #CodingInterview #Frontend #SoftwareEngineering
JavaScript Event Loop: Understanding Non-Blocking I/O
More Relevant Posts
-
JavaScript Hoisting: The Concept That Separates “I use JS” from “I understand JS” Hoisting is one of those JavaScript behaviors that silently explains why some code works, and why some bugs are so hard to catch. In JavaScript, code runs in two phases: 1️⃣ Compilation (creation) phase 2️⃣ Execution phase During compilation, JavaScript sets up memory for variables and functions. This is where hoisting happens. 🔹 var hoisting Only the declaration is hoisted, not the initialization. ex: console.log(x); // undefined var x = 5; Behind the scenes, JavaScript treats it like: var x; console.log(x); x = 5; No error, but also no value yet. This behavior has caused countless subtle bugs in real-world apps. 🔹 Function declarations Function declarations are fully hoisted, name and body. sayHello(); // works function sayHello() { console.log("Hello"); } This is why function declarations behave differently from function expressions. 🔹 let & const (ES6) They are hoisted, but not initialized. Accessing them before declaration throws a ReferenceError. console.log(y); // ReferenceError let y = 10; This period is known as the Temporal Dead Zone (TDZ), a design choice to make code safer and more predictable. 💡 Why this matters in real projects - Explains unexpected undefined - Helps debug scope-related issues - Shows you understand how JS actually works under the hood 📌 Best practice Don’t rely on hoisting. Write code that’s clear, intentional, and predictable, your future self (and your team) will thank you. #JavaScript #Frontend #WebDevelopment #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
🧵 How JavaScript Does 10 Things at Once (While Being Single-Threaded) 🔄 Ever wondered how JavaScript handles API calls, timers, or async tasks without freezing the browser UI? The secret is the Event Loop. Even though JavaScript is single-threaded (it can do only one thing at a time), the Event Loop allows it to be asynchronous and non-blocking. Here’s a simple 4-step breakdown of how it works 👇 1️⃣ Call Stack This is the “Now” zone. JavaScript executes synchronous code here. If a function is in the stack, the engine is busy. 2️⃣ Web APIs / Node APIs When you use `setTimeout`, `fetch`, or DOM events, JavaScript hands them off to the browser/Node environment. This keeps the call stack free so the UI doesn’t freeze. 3️⃣ Callback Queue & Microtask Queue Once async tasks complete, their callbacks wait here. 👉 Promises (Microtasks) always run before timers (`setTimeout`). 4️⃣ Event Loop This is the coordinator. It constantly checks: • Is the Call Stack empty? • If yes → move the next task from the queue to the stack. 🔑 Golden Rule: Avoid blocking the Event Loop with heavy synchronous code — otherwise users will experience laggy interfaces. Learning this really helped me understand async JavaScript better 🚀 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #EventLoop #Programming
To view or add a comment, sign in
-
-
🧵 How JavaScript Does 10 Things at Once (While Being Single-Threaded) 🔄 Ever wondered how JavaScript handles API calls, timers, or async tasks without freezing the browser UI? The secret is the Event Loop. Even though JavaScript is single-threaded (it can do only one thing at a time), the Event Loop allows it to be asynchronous and non-blocking. Here’s a simple 4-step breakdown of how it works 👇 1️⃣ Call Stack This is the “Now” zone. JavaScript executes synchronous code here. If a function is in the stack, the engine is busy. 2️⃣ Web APIs / Node APIs When you use `setTimeout`, `fetch`, or DOM events, JavaScript hands them off to the browser/Node environment. This keeps the call stack free so the UI doesn’t freeze. 3️⃣ Callback Queue & Microtask Queue Once async tasks complete, their callbacks wait here. 👉 Promises (Microtasks) always run before timers (`setTimeout`). 4️⃣ Event Loop This is the coordinator. It constantly checks: • Is the Call Stack empty? • If yes → move the next task from the queue to the stack. 🔑 Golden Rule: Avoid blocking the Event Loop with heavy synchronous code — otherwise users will experience laggy interfaces. Learning this really helped me understand async JavaScript better 🚀 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #EventLoop #Programming #javascript
To view or add a comment, sign in
-
-
🚀 The Complete Guide to JavaScript Module Bundlers: From Script Tags to Modern Build Tools JavaScript didn’t start with bundlers, tree-shaking, or blazing-fast builds. It started with <script> tags, global scope chaos, and dependency nightmares. In this deep-dive guide, I explore how we went from fragile script ordering to highly optimized, native-speed build pipelines—and why it matters for modern frontend and full-stack engineers in 2025. 🔍 What this guide covers: 🧱 The global scope problem & how IIFEs and namespaces tried to fix it ⚔️ The Module System Wars: CommonJS vs AMD vs UMD vs ESM 🌳 Tree shaking, scope hoisting, code splitting & side effects—explained visually 🛠️ A deep technical comparison of modern bundlers: Webpack (the Swiss Army knife) Rollup (the library specialist) esbuild (the speed demon) Rspack (Webpack reborn in Rust) Rolldown (Vite’s future) Bun (the all-in-one disruptor) 🧠 When to choose which bundler based on real-world constraints 🔮 Where JavaScript build tooling is heading (Rust, Zig, ESM-only future) ⚡ Key takeaway: Bundlers are no longer just “build tools.” They are performance engines, architectural enablers, and developer experience multipliers. If you work with JavaScript, TypeScript, React, Node.js, or modern web platforms, this guide will help you make smarter decisions—and understand why the ecosystem evolved this way. 📖 Read, learn, and share with your team. 👉 Read the full deep dive here - https://lnkd.in/gr-3XNqF #JavaScript #WebDevelopment #FrontendEngineering #BuildTools #Webpack #Rollup #esbuild #Rspack #Bun #Vite #ESModules #TypeScript #SoftwareArchitecture #DeveloperExperience #PerformanceEngineering
To view or add a comment, sign in
-
-
🧠 99% of JavaScript devs get this event loop question wrong 👀 (Even seniors pause before answering) No frameworks. No libraries. Just how JavaScript actually schedules work. 🧩 Output-Based Question (Event Loop: sync vs microtasks vs macrotasks) console.log("start"); setTimeout(() => { console.log("timeout"); }, 0); Promise.resolve().then(() => { console.log("promise"); }); (async function () { console.log("async"); })(); console.log("end"); ❓ What will be printed — in the correct order? ❌ Don’t run the code 🧠 Think like the JavaScript engine A. start → async → end → promise → timeout B. start → end → async → promise → timeout C. start → async → promise → end → timeout D. start → promise → async → end → timeout 👇 Drop your answer in the comments (no cheating 😄) Why this question matters This tests whether you truly understand: • synchronous execution • the event loop • microtasks vs macrotasks • why Promise.then beats setTimeout(0) • async IIFEs vs promises Many developers “use” async code every day — but few understand when it actually runs. Good JavaScript developers don’t memorize outputs. They understand how the engine thinks. 💡 I’ll pin the full explanation after a few answers. #JavaScript #EventLoop #AsyncJavaScript #WebDevelopment #ProgrammingFundamentals #InterviewPrep #MCQ #DeveloperTips #CodeQuality
To view or add a comment, sign in
-
-
🤔 Quick question: When JavaScript runs async code, where does everything actually go? After learning about the Call Stack and Event Loop, I realized something important: JavaScript doesn’t work alone — it collaborates with Web APIs and queues 👇 --------------------------- console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); ---------------------------- Output: - Start - End - Timeout 💡 What happens behind the scenes? - console.log("Start") → pushed to the Call Stack - setTimeout → handed off to Web APIs - console.log("End") → runs immediately Once the Call Stack is empty: - Event Loop checks the Task Queue - setTimeout callback is pushed back to the stack - Callback executes How the pieces fit together Call Stack → executes JavaScript Web APIs → handle timers, DOM events, network calls Queues → hold callbacks waiting to run Event Loop → coordinates everything Takeaway JavaScript executes code using the Call Stack, offloads async work to Web APIs, and uses the Event Loop to decide when callbacks can run. #JavaScript #WebDevelopment #FullStack #LearningInPublic
To view or add a comment, sign in
-
🚨 Rules of Hooks (and the Common Mistakes We Still Make) 🚨 React Hooks are powerful — but only if used correctly. Breaking the Rules of Hooks can lead to unexpected bugs, broken state, and hard-to-debug issues. Let’s break it down 👇 ✅ The 2 Golden Rules of Hooks 🔹 1. Call Hooks only at the top level ❌ Don’t call Hooks inside loops, conditions, or nested functions ✔ Always call them at the top of your component or custom Hook Why? React relies on the order of Hooks to manage state correctly. // ❌ Wrong if (isLoggedIn) { useEffect(() => {}, []); } // ✅ Correct useEffect(() => { if (isLoggedIn) {} }, [isLoggedIn]); 🔹 2. Call Hooks only from React functions ❌ Not inside normal JS functions ✔ Only inside: - Functional Components - Custom Hooks ⚠️ Common Hook Violations Developers Make 🚫 Conditional useEffect or useState 🚫 Calling Hooks inside callbacks or event handlers 🚫 Using Hooks inside class components 🚫 Forgetting dependencies in useEffect 🛠 Best Practices to Avoid Issues ✔ Extract reusable logic into custom Hooks ✔ Always think in terms of render cycles ✔ Treat Hooks as declarative logic, not utilities 💡 Remember: Hooks are not just functions — they are part of React’s internal state system. Mastering the Rules of Hooks = fewer bugs + cleaner code + better interviews 🚀 #ReactJS #Hooks #FrontendDevelopment #JavaScript #WebDevelopment #MERN #ReactHooks #CleanCode #CodingTips #DeveloperMistakes #SoftwareEngineering #LearningReact #FrontendTips
To view or add a comment, sign in
-
Understanding why Promise.all() needs an array in JavaScript Many developers try this and get confused 👇 ❌ Wrong way Promise.all(p1, p2); ✅ Correct way Promise.all([p1, p2]); 🤔 Why does this happen? Promise.all() accepts only ONE argument, and that argument must be an iterable (most commonly an array). 👉 An array allows JavaScript to loop through multiple promises and wait for all of them to resolve. ✅ Working example let p1 = new Promise((resolve) => { resolve(1); }); let p2 = new Promise((resolve) => { resolve(2); }); Promise.all([p1, p2]) .then((data) => { console.log(data); // [1, 2] }); ❌ Why `Promise.all(p1, p2)` throws an error? When you write: Promise.all(p1, p2); JavaScript treats it as: Promise.all(p1); But p1 is a "Promise object", not an iterable like an array. So JS throws: TypeError: object is not iterable 🧠 Easy way to remember > Promise.all waits for a collection of promises, not individual ones Always wrap promises inside an array. ⚠️ One more important thing If any promise rejects, Promise.all() immediately rejects. Promise.all([Promise.resolve(1), Promise.reject("Error")]) .catch(console.error); // Error 💡 Hope this helps someone avoid a common JavaScript pitfall! . . . . . #SRYTAL #JavaScript #Promises #WebDevelopment #Frontend #Learning #Promise.all #Growtogether
To view or add a comment, sign in
-
🧠 Microtasks vs Macrotasks in JavaScript If you’ve ever wondered why Promise.then() runs before setTimeout(), this is the reason 👇 🔹 What are Macrotasks? Macrotasks are large tasks scheduled to run later. Examples: setTimeout setInterval setImmediate (Node.js) DOM events I/O operations setTimeout(() => { console.log("Macrotask"); }, 0); 🔹 What are Microtasks? Microtasks are high-priority tasks that run immediately after the current execution, before any macrotask. Examples: Promise.then / catch / finally queueMicrotask MutationObserver Promise.resolve().then(() => { console.log("Microtask"); }); 🔹 Execution Order (Very Important 🔥) console.log("Start"); setTimeout(() => console.log("Macrotask"), 0); Promise.resolve().then(() => console.log("Microtask")); console.log("End"); Output: Start End Microtask Macrotask 🔹 Why This Happens? JavaScript follows this rule: 1️⃣ Execute synchronous code 2️⃣ Run all microtasks 3️⃣ Run one macrotask 4️⃣ Repeat 👉 Microtask queue is always drained first 🔹 Common Interview Gotcha 😅 setTimeout(() => console.log("timeout"), 0); Promise.resolve() .then(() => console.log("promise 1")) .then(() => console.log("promise 2")); Output: promise 1 promise 2 timeout 💡 Takeaway Microtasks = urgent callbacks Macrotasks = scheduled callbacks Understanding this helps you: ✅ Debug async bugs ✅ Avoid UI freezes ✅ Write predictable async code If this cleared up the event loop for you, drop a 👍 #JavaScript #EventLoop #AsyncJS #FrontendDevelopment
To view or add a comment, sign in
-
𝐯𝐚𝐫 𝐯𝐬. 𝐥𝐞𝐭 𝐯𝐬. 𝐜𝐨𝐧𝐬𝐭: The JavaScript Evolution 🧬 The way we declare variables has changed, and if you are still using `var` in 2026, it might be time for an upgrade! Here is the quick breakdown of the three keywords: 1️⃣𝐯𝐚𝐫 (𝐓𝐡𝐞 𝐎𝐥𝐝 𝐆𝐮𝐚𝐫𝐝) 👴 • 𝐒𝐜𝐨𝐩𝐞: Function Scoped. It ignores block boundaries like `if` or `for` loops, which can lead to variables leaking where they shouldn't. • 𝐇𝐨𝐢𝐬𝐭𝐢𝐧𝐠: It moves to the top and is initialized as `undefined`. This lets you access it before declaration (but it will be undefined). • 𝐁𝐞𝐬𝐭 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐞: Avoid it in modern development. 2️⃣𝐥𝐞𝐭 (𝐓𝐡𝐞 𝐌𝐨𝐝𝐞𝐫𝐧 𝐕𝐚𝐫𝐢𝐚𝐛𝐥𝐞) 🆕 • 𝐒𝐜𝐨𝐩𝐞: Block Scoped. It stays safely inside the `{ curly braces }`. • 𝐇𝐨𝐢𝐬𝐭𝐢𝐧𝐠: It is hoisted, but stays in the 𝐓𝐞𝐦𝐩𝐨𝐫𝐚𝐥 𝐃𝐞𝐚𝐝 𝐙𝐨𝐧𝐞 (𝐓𝐃𝐙). You cannot touch it before the line where it is defined. • 𝐔𝐬𝐞 𝐂𝐚𝐬𝐞: Use this for values that 𝑤𝑖𝑙𝑙 change (like loop counters). 3️⃣𝐜𝐨𝐧𝐬𝐭 (𝐓𝐡𝐞 𝐒𝐭𝐫𝐢𝐜𝐭 𝐎𝐧𝐞) 🔒 • 𝐒𝐜𝐨𝐩𝐞: Block Scoped (just like `let`). • 𝐑𝐮𝐥𝐞: You 𝐦𝐮𝐬𝐭 initialize it immediately, and you 𝐜𝐚𝐧𝐧𝐨𝐭 reassign it. • 𝐓𝐡𝐞 𝐆𝐨𝐭𝐜𝐡𝐚: It makes the 𝑏𝑖𝑛𝑑𝑖𝑛𝑔 immutable, not the 𝑣𝑎𝑙𝑢𝑒. If you make an object `const`, you can still change its properties! 🤯 𝐏𝐫𝐨 𝐓𝐢𝐩: Default to `const`. If you realize you need to change the value later, only then switch it to `let`. Check out the comparison table below! 👇 Do you have a strict linter rule to ban `var` in your projects? #JavaScript #WebDevelopment #ES6 #CodingBestPractices #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development