Microtasks vs Macrotasks — How JavaScript Really Schedules Work Ever wondered why this runs the way it does? 👇 console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D"); Output: A D C B This isn’t a JavaScript “gotcha” it’s how the JS runtime is designed. Behind the scenes, JavaScript uses two task queues: Microtasks → Promise.then, queueMicrotask Macrotasks → setTimeout, setInterval, UI events 🔑 Key rule After the call stack is empty: 👉 Microtasks are executed first (completely) 👉 Then one macrotask is picked 👉 Repeat That’s why promises feel faster than timers. 💡 Why this matters for frontend devs Prevent UI freezes Avoid async race conditions Write smoother React/Vue apps Debug “why did this run before that?” bugs Understand how browsers actually schedule work I wrote a deep-dive Medium article breaking down: ✔ Why JS needs task queues ✔ Call stack & event loop ✔ Microtasks vs macrotasks (with real examples) ✔ Common mistakes even experienced devs make 📖 Read the full article here: 👉 https://lnkd.in/dQr6dKkP If you’ve ever been confused by async JavaScript this one’s for you. #JavaScript #FrontendDevelopment #WebDevelopment #EventLoop #Promises #Performance #React #BrowserInternals
JavaScript Task Queues: Microtasks vs Macrotasks Explained
More Relevant Posts
-
🔥 JavaScript Event Loop Explained (Simply) JavaScript is single-threaded. But then how does this work? 👇 console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Most developers get this wrong in interviews. Let’s break it down properly 👇 🧠 1️⃣ Call Stack Think of the Call Stack as: The place where JavaScript executes code line by line. It follows LIFO (Last In, First Out). console.log("Start") → runs immediately console.log("End") → runs immediately Simple so far. 🌐 2️⃣ Web APIs When JavaScript sees: setTimeout() It sends it to the browser’s Web APIs. Web APIs handle: setTimeout DOM events fetch Geolocation JavaScript doesn’t wait for them. 📦 3️⃣ Callback Queue (Macrotask Queue) After setTimeout finishes, its callback goes into the Callback Queue. But it must wait… Until the Call Stack is empty. ⚡ 4️⃣ Microtask Queue Promises don’t go to the normal queue. They go to the Microtask Queue. And here’s the important rule 👇 Microtasks run BEFORE macrotasks. So the execution order becomes: 1️⃣ Start 2️⃣ End 3️⃣ Promise 4️⃣ Timeout 🎯 Final Output: Start End Promise Timeout 💡 Why This Matters Understanding the Event Loop helps you: ✔ Debug async issues ✔ Write better Angular apps ✔ Avoid race conditions ✔ Pass senior-level interviews Most developers memorize async code. Senior developers understand the Event Loop. Which one are you? 👀 #JavaScript #Angular #Frontend #WebDevelopment #EventLoop #Async
To view or add a comment, sign in
-
-
🚀 JavaScript Event Loop – The Real Game Changer Behind Async Code Most developers use setTimeout, Promises, or async/await daily… But very few truly understand what’s happening behind the scenes. Let’s break down the JavaScript Event Loop 👇 🧠 First, Understand This: JavaScript is single-threaded. It has: • Call Stack • Web APIs (Browser / Node environment) • Microtask Queue • Macrotask Queue • Event Loop 📌 How It Works: 1️⃣ Code runs line by line in the Call Stack. 2️⃣ Async operations move to Web APIs. 3️⃣ When completed, they move to: • Microtask Queue → Promise.then, catch, finally • Macrotask Queue → setTimeout, setInterval 4️⃣ Event Loop checks: • Is Call Stack empty? • If yes → Run ALL Microtasks first • Then run ONE Macrotask • Repeat 💡 Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 👉 Output: Start End Promise Timeout Why? Because Microtasks (Promises) always execute before Macrotasks (setTimeout). 🎯 Why This Matters: Understanding the Event Loop helps you: • Debug async issues • Improve performance • Build real-time applications • Crack senior-level JavaScript interviews 🔥 Advanced Insight: In engines like V8 (used in Chrome and Node.js): • Call Stack uses stack memory • Objects are stored in heap memory • Garbage Collector cleans unused memory • Event Loop coordinates task execution JavaScript feels multi-threaded… But it's actually an illusion created by the Event Loop. If you had to explain it in one sentence: “The Event Loop is the traffic controller of asynchronous JavaScript.” #javascript #webdevelopment #nodejs #reactjs #async #eventloop #programming #softwareengineering
To view or add a comment, sign in
-
-
JSX Conditional Rendering Isn’t Magic — It’s JavaScript + React Rules If you’ve ever been confused by code like this: {list.length && <List />} and wondered “Why is 0 rendering?” — this post is for you. The confusion comes from mixing JavaScript evaluation rules with React rendering rules. They happen in two different phases. 🟨 Phase 1: JavaScript (Evaluation) Before React does anything, JavaScript evaluates the expression. Key rule of &&: A && B If A is falsy → return A If A is truthy → return B Falsy values in JS: false, 0, "", null, undefined, NaN Important: && returns a value, not true or false Arrays ([]) are truthy 0 is falsy, but still a number Example: 0 && <List /> // → 0 true && <List /> // → <List /> false && "Hi" // → false JavaScript stops here. 🟦 Phase 2: React (Rendering) React now receives the result and decides whether it can be rendered. 🚫 React does NOT render: false true null undefined ✅ React DOES render: 0 "" "hello" NaN Why? Booleans are control flags null / undefined mean absence Numbers & strings are real UI data ❌ The Classic Bug {list.length && <List />} If list = []: list.length === 0 0 && <List /> // JS returns 0 React receives 0 → renders 0 😬 ✅ Correct Patterns Render only when list has items: {list.length > 0 && <List />} Render when list exists: {list && <List />} Render empty state: {!list.length && <EmptyState />} 🧠 Mental Model (Remember This) JavaScript decides WHAT the expression evaluates to React decides WHETHER that result is renderable Falsy ≠ hidden Only false, null, and undefined are hidden by React. 🔑 Final Takeaway JSX isn’t inconsistent — it’s predictable once you separate JavaScript rules from React rules. Most “weird JSX bugs” disappear the moment you think in these two phases. 💬 Have you ever accidentally rendered 0 in production? You’re definitely not alone. #React #JavaScript #JSX #Frontend #WebDevelopment #ReactTips #Engineering
To view or add a comment, sign in
-
-
Understanding JavaScript's Asynchronous Magic ✨ Ever wondered how JavaScript, a single-threaded language, handles complex tasks without freezing your application? It's all thanks to its clever asynchronous nature! JavaScript executes code synchronously using a call stack. If a long-running task runs here, it blocks everything. Imagine your entire web page freezing while waiting for a single operation – not ideal for user experience! To avoid this, JavaScript delegates asynchronous tasks (like timers, network requests, or database calls) to the browser's Web APIs. These APIs work in the background, freeing up the main JavaScript thread to continue executing other code. Once an asynchronous task is complete, its associated callback function isn't immediately thrown back into the call stack. Instead, it's placed into a queue: Microtask Queue: For promises and queueMicrotask. Callback Queue (or Macrotask Queue): For timers (setTimeout, setInterval), I/O, and UI rendering. This is where the Event Loop comes in! 🔄 The Event Loop constantly monitors the call stack. When the call stack is empty (meaning all synchronous code has finished executing), the Event Loop steps in. It first checks the Microtask Queue and pushes any pending callbacks onto the call stack for execution. Once the Microtask Queue is empty, it then moves on to the Callback Queue, taking the oldest callback and pushing it onto the call stack. This continuous dance between the call stack, Web APIs, queues, and the Event Loop is how JavaScript achieves its non-blocking asynchronous behavior, giving users a smooth and responsive experience – all without ever becoming truly multi-threaded! Pretty neat, right? This fundamental concept is crucial for building performant and scalable web applications. #JavaScript #WebDevelopment #Frontend #Programming #AsynchronousJS #EventLoop
To view or add a comment, sign in
-
-
🚀 Top 20 JavaScript Concepts Every Developer Must Master. 1️⃣ Hoisting JavaScript moves variable and function declarations to the top of their scope before execution. 2️⃣ Closures A function that remembers variables from its outer scope even after the outer function has finished. 3️⃣ Scope (Global, Function, Block) Determines where variables are accessible. 4️⃣ Lexical Scope Scope is decided by where functions are written, not where they are called. 5️⃣ Prototypes & Inheritance JavaScript uses prototypal inheritance to share properties and methods between objects. 6️⃣ Event Loop Handles asynchronous operations in JavaScript’s single-threaded environment. 7️⃣ Call Stack Tracks function execution order. 8️⃣ Async/Await Cleaner way to handle asynchronous code using promises. 9️⃣ Promises Represents a value that may be available now, later, or never. 🔟 Callback Functions Functions passed as arguments to other functions. 1️⃣1️⃣ Debounce & Throttle Improve performance by controlling how often functions run. 1️⃣2️⃣ Event Delegation Attach event listeners to parent elements instead of multiple children. 1️⃣3️⃣ Truthy & Falsy Values Understanding how JavaScript evaluates values in conditions. 1️⃣4️⃣ Type Coercion JavaScript automatically converts types (== vs === difference). 1️⃣5️⃣ Destructuring Extract values from arrays or objects easily. 1️⃣6️⃣ Spread & Rest Operators Expand arrays/objects or collect function arguments. 1️⃣7️⃣ ES6 Modules Organize and reuse code using import and export. 1️⃣8️⃣ Memory Management & Garbage Collection JavaScript automatically allocates and frees memory. 1️⃣9️⃣ IIFE (Immediately Invoked Function Expression) Function that runs immediately after it’s defined. 2️⃣0️⃣ The " this" Keyword 'this'refers to the object that is calling the function. Its value depends on how the function is invoked (not where it’s defined). In arrow functions, this is inherited from the surrounding scope. #JavaScript #FrontendDeveloper #BackendDeveloper #WebDevelopment #FullstackDeveloper #Developers
To view or add a comment, sign in
-
-
What is non-blocking operation in JavaScript? Non-blocking in JavaScript means your code can start a slow task (like a timer, API call, or file read) and keep executing other code instead of waiting and freezing the main thread. Brief explanation JavaScript runs on a single thread with an event loop. When it hits an async operation (setTimeout, fetch, I/O), that work is offloaded to Web APIs / the system. When the async work finishes, its callback is queued and later pushed back to the call stack by the event loop, so the main thread never blocks while waiting. Simple example for your post js console.log("Start"); setTimeout(() => { console.log("Inside setTimeout (runs later)"); }, 2000); // 2 seconds console.log("End"); Output: Start End Inside setTimeout (runs later) Even though the timer is 2 seconds, "End" prints immediately. The setTimeout callback is handled in the background and executed later via the event loop, so the main thread is not blocked. Ready-to-post LinkedIn text JavaScript is single-threaded, but it still feels “non-blocking” thanks to the event loop.🧵 When we use functions like setTimeout, fetch, or other async APIs, JavaScript does not wait for them to finish. Instead, the heavy work is offloaded to the browser/Web APIs or Node’s libuv layer. Once the operation completes, its callback is pushed to a queue, and the event loop runs it when the call stack is free. Example: js console.log("Start"); setTimeout(() => { console.log("Inside setTimeout (runs later)"); }, 2000); console.log("End"); Output order: Start → End → Inside setTimeout (runs later) This is a simple demo of non-blocking behavior: while the timer is counting in the background, the main thread continues executing the rest of the code, keeping the UI responsive and allowing servers to handle many requests concurrently #javascript #frontendDevelopment #react #reactjs
To view or add a comment, sign in
-
𝐘𝐨𝐮𝐫 `𝐮𝐬𝐞𝐌𝐞𝐦𝐨` 𝐢𝐬𝐧'𝐭 𝐚𝐥𝐰𝐚𝐲𝐬 𝐝𝐨𝐢𝐧𝐠 𝐰𝐡𝐚𝐭 𝐲𝐨𝐮 𝐭𝐡𝐢𝐧𝐤 𝐢𝐭 𝐢𝐬, 𝐞𝐬𝐩𝐞𝐜𝐢𝐚𝐥𝐥𝐲 𝐰𝐢𝐭𝐡 𝐨𝐛𝐣𝐞𝐜𝐭𝐬. I've seen so many teams struggle with React performance, reaching for `useMemo` like it's a silver bullet. But if you're memoizing a component, and its props include an object or array created inline, you might still be triggering unnecessary re-renders. Why? JavaScript's reference equality. ```javascript // The common pitfall: const MyComponent = React.memo(({ config }) => { /* ... */ }); function Parent() { // `configObject` is a new object on every render const configObject = { theme: 'dark', size: 'medium' }; return <MyComponent config={configObject} />; } ``` Even if `theme` and `size` values are the same, `configObject` is a new reference each time `Parent` renders. `React.memo` sees a new prop and re-renders `MyComponent`. The fix? Memoize the object itself: ```javascript const MyComponent = React.memo(({ config }) => { /* ... */ }); function Parent() { const configObject = useMemo(() => ({ theme: 'dark', size: 'medium' }), []); // Empty dependency array means it's created once return <MyComponent config={configObject} />; } ``` Now, `configObject` maintains its reference across `Parent` renders, letting `React.memo` on `MyComponent` actually do its job. This small detail can make a massive difference in complex applications with deeply nested or frequently updating components. It's not about premature optimization, it's about understanding how React and JavaScript work together. What's a subtle React performance trap you've encountered and fixed? #React #Frontend #JavaScript #WebDevelopment #Performance
To view or add a comment, sign in
-
🤔 Promise vs async/await in JavaScript (What’s the Real Difference?) Both Promises and async/await handle asynchronous operations in JavaScript—but the way you write and read the code is very different. 🔹 Promise (then/catch) fetchData() .then(data => { console.log(data); return processData(data); }) .then(result => { console.log(result); }) .catch(error => { console.error(error); }); ✔ Works everywhere ✔ Powerful chaining ❌ Can become hard to read with multiple steps 🔹 async/await (Cleaner syntax) async function loadData() { try { const data = await fetchData(); const result = await processData(data); console.log(result); } catch (error) { console.error(error); } } ✔ Reads like synchronous code ✔ Easier debugging & error handling ✔ Better for complex flows 🔹 Key Difference (Important!) 👉 async/await is just syntactic sugar over Promises Under the hood: async function always returns a Promise await pauses execution until the Promise resolves/rejects 🔹 Error Handling // Promise promise.catch(err => console.log(err)); // async/await try { await promise; } catch (err) { console.log(err); } try/catch often feels more natural for real-world apps. 🔹 When to Use What? ✅ Use Promises when: Simple one-liner async logic Parallel execution with Promise.all ✅ Use async/await when: Multiple async steps Conditional logic or loops Readability matters (most of the time) 💡 Takeaway Promises are the engine async/await is the comfortable driving experience If you’re writing modern JavaScript… async/await should be your default choice 🚀 Which one do you prefer in production code—and why? 👇 #JavaScript #AsyncJS #FrontendDevelopment #WebDevelopment
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗕𝗮𝘀𝗶𝗰𝘀 𝗢𝗳 𝗥𝗲𝗮𝗰𝘁 You want to build efficient frontend applications. React is a JavaScript library that helps you do this. Before React, updating a webpage was messy. You had to manually change the DOM, which was tedious and hard to scale. React compares the old and new virtual DOM and renders only the changes when you update a state. Let's start with the basics: - Components are reusable code segments that return JSX. - JSX is a syntax extension for JavaScript that lets you write HTML-like code in a JavaScript file. - A component can only return one JSX tag, so you need to wrap multiple tags in a container. - Props help components interact with each other by passing parameters. - State is a component's memory, which changes when you interact with it. - Hooks like useState, useContext, and useRef help you manage state and references. You can also create your own hooks. When you build a component, you need to export it so it can be used in other files. React's main job is rendering, but it also handles side effects like fetching data or updating the page title. The useEffect Hook helps you do this. It runs after React finishes rendering and keeps your UI logic clean. You can control when the effect runs by using a dependency array. This is a basic intro to React. You need to learn more to become proficient. Source: https://react.dev/learn
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