🚀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗮𝘀𝘆𝗻𝗰/𝗮𝘄𝗮𝗶𝘁: 𝘄𝗵𝘆 𝗶𝘁 𝗹𝗼𝗼𝗸𝘀 𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗯𝘂𝘁 𝗶𝘀𝗻’𝘁 JavaScript doesn’t execute async/await synchronously; it only makes asynchronous code easier to read. Example: console.log("A"); async function test() { console.log("B"); await Promise.resolve("C"); console.log("D"); } test(); console.log("E"); Output: A B E D What actually happens: 1) Global execution starts "A" is printed 2) test() is called "B" is printed 3) await Promise.resolve("C") • The promise is already resolved, but await still pauses, 𝗮𝘄𝗮𝗶𝘁 𝗻𝗲𝘃𝗲𝗿 𝗰𝗼𝗻𝘁𝗶𝗻𝘂𝗲𝘀 𝗶𝗺𝗺𝗲𝗱𝗶𝗮𝘁𝗲𝗹𝘆 • Suspends test execution and lets the rest of the code run first • The remaining code (console.log("D")) is scheduled as a microtask 4) Global code continues "E" is printed 5) Microtask queue runs async function resumes from where it paused "D" is printed See? Nothing got blocked. That’s JavaScript for you, and async/await just keeps async code readable. Thanks to Akshay Saini 🚀 for explaining this concept in Namaste Javascript, which made async/await click for me! 👏👏 #JavaScript #AsyncAwait #EventLoop #FrontendDevelopment #WebDevelopment
JavaScript async/await explained
More Relevant Posts
-
🤔 Quick question: If JavaScript is single-threaded, who decides when async code runs? When I first heard about the Event Loop, I imagined something very complex. Turns out… it’s just a coordinator that decides when JavaScript can execute async callbacks 👇 -------------------------------- console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); -------------------------------- Output: - Start - End - Promise - Timeout 💡 High-level mental model: - JavaScript executes synchronous code using the Call Stack - Async tasks are handled by the runtime environment - When the stack is empty, the Event Loop checks: - Microtasks (Promises) - Then macro tasks (setTimeout, events) - It pushes the next callback onto the stack for execution Takeaway: The event loop is what makes asynchronous javascript possible. It doesn’t run code in parallel — it decides when callbacks can run. 👉 Did this execution order surprise you the first time you saw it? #JavaScript #WebDevelopment #FullStack #LearningInPublic
To view or add a comment, sign in
-
JavaScript feels simple… until someone asks: 𝐂𝐚𝐧 𝐲𝐨𝐮 𝐞𝐱𝐩𝐥𝐚𝐢𝐧 𝐡𝐨𝐰 𝐭𝐡𝐢𝐬 𝐜𝐨𝐝𝐞 𝐫𝐮𝐧𝐬 𝐢𝐧𝐭𝐞𝐫𝐧𝐚𝐥𝐥𝐲? Initially, JavaScript felt magical to me. Hoisting. Call stack. Async. I was just memorizing rules, not understanding what was really happening. Then I learned the Execution Context + Call Stack mental model (thanks to Akshay Saini 🚀 ) — and suddenly, everything clicked. 𝐇𝐨𝐰 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐚𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐫𝐮𝐧𝐬: JavaScript runs inside an Execution Context. It starts with the 𝐆𝐥𝐨𝐛𝐚𝐥 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐂𝐨𝐧𝐭𝐞𝐱𝐭. It’s just an environment where your code is prepared and then run. Each execution context has two phases: 𝐌𝐞𝐦𝐨𝐫𝐲 𝐩𝐡𝐚𝐬𝐞 • Memory is allocated to variables and functions • Variables get a placeholder value: undefined • Functions are stored completely 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐩𝐡𝐚𝐬𝐞 • Code runs line by line • Values are assigned to variables • When a function is called, a new execution context is created • When the function finishes, its context is removed 𝐖𝐡𝐨 𝐦𝐚𝐧𝐚𝐠𝐞𝐬 𝐚𝐥𝐥 𝐭𝐡𝐢𝐬? The Call Stack • Global Execution Context goes first • Each function call goes on top • When finished → it gets popped off Credits to Akshay Saini 🚀 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐃𝐞𝐞𝐩 𝐃𝐢𝐯𝐞 𝐩𝐥𝐚𝐲𝐥𝐢𝐬𝐭: https://lnkd.in/gy5ypSGf Blog: https://lnkd.in/gd8ZFDiJ #javascript #webdevelopment #interviews #engineering #learning #namastejavascript #namastejs #namastedev #akshaysaini #nodejs #systemdesign
To view or add a comment, sign in
-
-
Callbacks vs Promises vs Async/Await in JavaScript Handling asynchronous code is a core part of JavaScript. Over time, the language has evolved to make async code easier to read, write, and maintain. Callbacks - Callbacks were the original way to handle async operations. A function is passed as an argument and executed after a task completes. While simple at first, callbacks can quickly lead to deeply nested code, often called “callback hell,” which is hard to debug and maintain. Promises - Promises improved async handling by representing a value that will be available in the future. They make code more structured and readable using then and catch. Promises reduce nesting, but complex chains can still become difficult to follow. Async/Await - Async and await are built on top of promises but make async code look synchronous. This improves readability, simplifies error handling with try and catch, and makes the flow of logic much clearer. When to use what - Callbacks work for very small tasks - Promises are good for chaining async operations - Async and await are best for clean, readable, and scalable code Modern JavaScript heavily favors async and await for most real-world applications. Clean async code leads to better performance, fewer bugs, and happier developers. #JavaScript #WebDevelopment #AsyncProgramming #FrontendDevelopment #SoftwareEngineering Ankit Mehra Kausar Mehra Manoj Kumar (MK) TechRBM PUNKAJJ DAAS Nikhil Jain Sunil Singh Divyajot Angrish Meenakshi Sharma
To view or add a comment, sign in
-
-
🚀 Day 3 Not Just Motivation — Real Concepts to Build Strong Technical Understanding (Part 3) JavaScript Concept That Finally Made Everything Clear: Global Execution Context (GEC) Most JavaScript confusion doesn’t come from complex syntax. It comes from not knowing how JavaScript starts executing your code. Before the first line runs, JavaScript does something very important. 👇 It creates the Global Execution Context (GEC). What really happens when a JS file runs? 🔹 Step 1: GEC is created This is the default execution environment for your program. 🔹 Step 2: GEC is pushed into the Call Stack Yes — the Call Stack starts with GEC. And since the Call Stack follows LIFO (Last In, First Out): GEC stays at the bottom until everything finishes. No function can execute unless GEC already exists. GEC works in two phases (this is key) 1️⃣ Memory Creation Phase (Preparation) Memory is allocated before execution var → undefined Functions → full definition stored let / const → exist but uninitialized (TDZ) 👉 This explains hoisting without any mystery. 2️⃣ Execution Phase Code runs line by line Variables get actual values Functions create their own execution contexts Each new context goes on top of the Call Stack And when a function finishes? 👉 Its execution context is popped off the stack (LIFO in action). One subtle but important detail In the global execution context: Browser → this === window Node.js → this === global Why this concept matters Once you truly understand GEC: Hoisting stops being confusing Call Stack behavior makes sense Async concepts feel more logical Debugging becomes easier 📌 Key takeaway JavaScript doesn’t jump into execution. It prepares memory, sets context, pushes GEC to the Call Stack — then starts running your code. If JavaScript ever felt unpredictable, it’s not chaos. It’s a well-defined execution model — once you see it, you can’t unsee it. #JavaScript #ExecutionContext #CallStack #React #Frontend #TechConcepts #LearningInPublic
To view or add a comment, sign in
-
🚀 Event Loop Deep Dive — How JavaScript Really Executes Your Code Most developers use async JavaScript every day… but very few truly understand how it actually works under the hood. JavaScript is single threaded, yet it handles: • API calls • timers • promises • user interactions So what’s the secret? 👉 The Event Loop I just published a deep-dive article where I break this down step by step: ✔ How JavaScript executes synchronous code ✔ What really happens inside the Call Stack ✔ Global Execution Context explained visually ✔ Microtasks vs Macrotasks (Promises vs setTimeout) ✔ Why execution order surprises even experienced devs No shortcuts. No magic. Just how JavaScript really works. If you’ve ever been confused by execution order or faced weird async bugs this one’s for you. 📖 Read the full article here: 🔗 https://lnkd.in/dbUCv6N5 #JavaScript #EventLoop #WebDevelopment #Frontend #SoftwareEngineering #AsyncJS #React #NodeJS
To view or add a comment, sign in
-
Ever looked at your async JavaScript code and thought, “Why is this so hard to follow?” 😅 You might be dealing with 𝗰𝗮𝗹𝗹𝗯𝗮𝗰𝗸 𝗵𝗲𝗹𝗹 aka 𝗣𝘆𝗿𝗮𝗺𝗶𝗱 𝗼𝗳 𝗗𝗼𝗼𝗺 💀 It happens when one async task is written inside another… then another… then another… Until your code becomes deeply nested and starts moving more sideways than forward. 𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝗯𝗲𝗰𝗼𝗺𝗲𝘀 𝗮 𝗿𝗲𝗮𝗹 𝗽𝗿𝗼𝗯𝗹𝗲𝗺 – ☑ Understanding the flow takes more time than writing new features⏳ ☑ Bugs hide deep inside the nesting 🐛 ☑ Error handling gets repeated everywhere 🔁 ☑ Small changes can break unexpected parts💥 Good news, this isn’t a JavaScript flaw... It is a design issue, and modern patterns help us write async code in a clean, step-by-step way instead of stacking callbacks ✨ Simple rule I follow, If your code keeps shifting right → refactor 🛠️ Have you faced callback hell in production?? 🤔 #FullStackDeveloper #MERNStack #JavaScript #WebDevelopment #FrontendDevelopment #AsyncProgramming #AsyncAwait #Promises #CallbackHell #CleanCode #SoftwareEngineering #DeveloperTips
To view or add a comment, sign in
-
-
JavaScript is single-threaded… Yet it handles asynchronous operations without blocking the main thread. Here’s what most developers don’t fully understand 👇 • res.json() returns a Promise because reading and parsing the response body is asynchronous. • Arrow functions don’t have their own this — they inherit it from the surrounding (lexical) scope. • map() returns a new array because it transforms each element, while forEach() doesn’t return anything — it simply executes logic for each item. • Promises don’t make code asynchronous — they help manage the result of asynchronous operations. • The event loop is what enables non-blocking behavior in JavaScript. Revisiting concepts like callbacks, promise chaining, async/await, error handling, APIs, JSON, HTTP verbs, prototypes, and inheritance made one thing clear: Understanding how JavaScript works internally changes how you write code. What JavaScript concept took you the longest to truly understand? 👇 #JavaScript #AsyncJavaScript #WebDevelopment #FullStackDevelopment #MERNStack #SoftwareDeveloper
To view or add a comment, sign in
-
-
💡 How JavaScript Code Executes (Behind the Scenes) Everything in JavaScript happens inside an Execution Context. You can imagine an execution context as a box with two parts: 1) Memory Component (Variable Environment) - Stores variables and functions as key-value pairs - Variables are stored as undefined - Functions store the entire function code 2) Code Component (Thread of Execution) - This is where the code runs - Code is executed line by line - JavaScript is synchronous and single-threaded What happens when a JavaScript program runs? When the program starts, a Global Execution Context is created. Execution happens in two phases: Memory Creation Phase - JavaScript scans the whole program - Memory is allocated to variables and functions Code Execution Phase - JavaScript executes code line by line - Values are assigned to variables - On function call, a new execution context is created Call Stack - Manages the order of execution - Global Execution Context is pushed first - Function contexts are pushed and popped after execution Understanding execution context helps in mastering hoisting, scope, closures, and async JavaScript. #JavaScript #WebDevelopment #Frontend #React #LearningInPublic
To view or add a comment, sign in
-
-
This async / await output confuses even experienced developers 🤯 🧩 JavaScript Output-Based Question (Async / Await) ✅ Correct Output 3 1 4 2 🧠 Why this output comes? (Step-by-Step) 1️⃣ Synchronous code runs first • console.log(3) → prints 3 2️⃣ test() is called • console.log(1) runs immediately → prints 1 3️⃣ await Promise.resolve() • Even though the promise is resolved, await pauses the function execution • Remaining code moves to the microtask queue 4️⃣ Back to synchronous code • console.log(4) → prints 4 5️⃣ Microtasks execute • console.log(2) runs last → prints 2 🔑 Key Takeaways (Interview Insight) ✔️ await is always asynchronous ✔️ Code after await runs in the microtask queue ✔️ Even resolved promises don’t run immediately ✔️ Understanding the event loop is critical for async JavaScript async / await looks synchronous, but behaves asynchronously. #JavaScript #AsyncAwait #InterviewQuestions #FrontendDeveloper #MERNStack #ReactJS
To view or add a comment, sign in
-
-
This async / await output confuses even experienced developers 🤯 🧩 JavaScript Output-Based Question (Async / Await) ✅ Correct Output 3 1 4 2 🧠 Why this output comes? (Step-by-Step) 1️⃣ Synchronous code runs first • console.log(3) → prints 3 2️⃣ test() is called • console.log(1) runs immediately → prints 1 3️⃣ await Promise.resolve() • Even though the promise is resolved, await pauses the function execution • Remaining code moves to the microtask queue 4️⃣ Back to synchronous code • console.log(4) → prints 4 5️⃣ Microtasks execute • console.log(2) runs last → prints 2 🔑 Key Takeaways (Interview Insight) ✔️ await is always asynchronous ✔️ Code after await runs in the microtask queue ✔️ Even resolved promises don’t run immediately ✔️ Understanding the event loop is critical for async JavaScript async / await looks synchronous, but behaves asynchronously. #JavaScript #AsyncAwait #InterviewQuestions #FrontendDeveloper #MERNStack #ReactJS
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