I ran this JavaScript snippet, and the output completely surprised me 😳. Day 10: How JavaScript actually handles a async operations ⚙️. 🧠 Logic: 🔹 JS execution always starts with synchronous code -> so "start", "First" & "end" log first. 🔹 Inside the loop, setTimeout is added to macrotask queue (it will run later). 🔹 Promise.then() is added to microtask queue (these will run right after sync code), cause of high priority then macrotask queue. 🔹 Inside asyncFn(), when execution hits await it pauses that function exec & waits for promise to get resolve. 🔹 In the mean time, event Loop continue with promise callback in microTask, one it's completed, the promise get resolved in asyncFn() & then it prints ("Second") to console. 🔹 And the last, the setTimeout callback in macroTask queue gets executed. So: ✅ Promise run first (microTasks). ⏱️ SetTimeout run after (macroTasks). That's why promise 0, promise 1, promise 2, and Second appear before all TimeOut logs. #Javascript #InterviewPrep #100DaysOfCode #CodingChallenge #JavaScript #CodingInterview #JSChallenges
How JavaScript handles async operations
More Relevant Posts
-
Came across a really clear article on the JavaScript Event Loop: “𝐓𝐡𝐞 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩 𝐄𝐱𝐩𝐥𝐚𝐢𝐧𝐞𝐝 𝐰𝐢𝐭𝐡 𝐄𝐱𝐚𝐦𝐩𝐥𝐞𝐬” short and practical. Great refresher on async tasks, microtasks vs macrotasks, and how the event loop works. The examples make it easy to connect theory with real code. If you work with JS, definitely worth a read! 🔗 https://lnkd.in/gwqhBxim #JavaScript #FrontendDevelopment #WebDevelopment #DeveloperLearning #React #EventLoop
To view or add a comment, sign in
-
🚀 Ever wondered what really happens behind the scenes when JavaScript runs your code? Even though JavaScript is single-threaded, it behaves like it’s multitasking — all thanks to its Runtime Environment ⚙️ 🧩 Here’s a simple breakdown that made async behavior click for me: 🔹 Call Stack — runs code line by line 🔹 Memory Heap — stores variables & objects 🔹 Web APIs — handle async tasks like fetch() and setTimeout() 🔹 Event Loop — keeps checking if the stack is free and pushes tasks from queues 🔹 Microtask & Callback Queues — decide what executes next Understanding this helped me write smoother async code and debug with confidence 💪 #JavaScript #WebDevelopment #Frontend #AsyncJS #ProgrammingConcepts #LearnInPublic #CodeNewbie #WebDevCommunity
To view or add a comment, sign in
-
-
🚀 Day 14 — JavaScript Event Loop 🔁 Today I learned one of the most magical parts of JavaScript — The Event Loop! ✨ Even though JavaScript is single-threaded, it can still handle asynchronous tasks like setTimeout, fetch, and Promises. Here’s what I understood 👇 🧠 Call Stack → Runs all normal (synchronous) code. 🌐 Web APIs → Handles async work like timers, DOM events, etc. 🕒 Callback Queue → Stores async callbacks waiting to run. ⚡ Microtask Queue → Stores promise callbacks (runs before callback queue). 🔁 Event Loop → Keeps checking if the call stack is empty and moves tasks from queues to stack. 💡 Key Lesson: - Promises run before setTimeout (microtasks run first). - The Event Loop helps JavaScript look asynchronous, even though it’s single-threaded! #JavaScript #EventLoop #WebDevelopment #100DaysOfCode #MERN #CodingJourney
To view or add a comment, sign in
-
-
Think JavaScript Await Is Same Everywhere? That’s Only Half Truth The behavior changes dramatically depending on where it’s being used. I recently learnt that the loop construct you choose completely changes how await behaves. Let me show you what I wish someone had explained to me six months ago, before I wasted hours debugging async/await issues. #javascript #typescript https://lnkd.in/d8ZB5XXG
To view or add a comment, sign in
-
How TypeScript ‘just knows’ the types from a plain JavaScript library? That magic comes from .𝗱.𝘁𝘀 𝗳𝗶𝗹𝗲𝘀 - Type Declaration files. They don’t contain any logic. They simply describe what a library exposes - the functions, parameters, return types, and more. So when you import something like "lodash", TypeScript instantly provides IntelliSense and type safety. All thanks to @types/lodash, which ships those .d.ts definitions. Without them? No autocomplete. No type hints. Just... guesswork. 😅 Think of .d.ts files as 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁’𝘀 𝗱𝗶𝗰𝘁𝗶𝗼𝗻𝗮𝗿𝘆 for JavaScript libraries — helping your editor speak fluent types even when the code doesn’t. Do you remember the first time you realized this? Or ever had to write one yourself? #TypeScript #JavaScript #WebDevelopment #Frontend #DevTips #CodeSmarter #IntelliSense #DefinitelyTyped #DeveloperExperience
To view or add a comment, sign in
-
-
🔒 JavaScript Closures: The Private Diary Analogy Ever wondered how JavaScript "remembers" things? Let me explain closures with a real-world analogy. Think of a closure like a private diary with a lock: 📖 The diary (outer function) contains your secrets (variables) 🔐 Only you have the key (inner function) to access those secrets ✨ Even after you close the diary, the key still works Why does this matter? The count variable is trapped inside the closure. No one can directly access or modify it from outside. It's like data privacy built into JavaScript! Real-world use case : This powers every search bar you've used that waits for you to stop typing! The key insight: Closures let inner functions remember their environment, even after the outer function has finished executing. Have you used closures in your code today? Share your favorite use case below! 👇 #JavaScript #WebDevelopment #ReactJS #Programming #Frontend #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
Ever wondered how JavaScript actually runs your code behind the scenes? 👀 I’ve created a quick-reference cheat sheet on JavaScript’s Dynamic Runtime — covering the Execution Context, Call Stack, Heap, Event Loop, and how JS manages async operations through its task queues. Feel free to download and share the PDF. Hope it helps! ⚡ #JavaScript #FrontendDevelopment #ProgrammingTips #AsyncProgramming #WebDev #JSRuntime #Developers #TechLearning
To view or add a comment, sign in
-
The Event Loop — What’s Really Happening Behind setTimeout()? JavaScript is single-threaded... but feels multitasked. Here’s the secret — ➡️ Tasks go to the call stack ➡️ Promises & timeouts go to microtask/macrotask queues ➡️ The Event Loop decides what runs next 🌀 Understand this, and async code will never confuse you again! #JavaScript #FrontendDevelopment #DevHackMondays #WebDevelopment #TechLearning
To view or add a comment, sign in
-
JavaScript Unique Magic: Hoisting Definition: Hoisting in JavaScript means moving all variable and function declarations to the top of their scope before the code runs. This allows you to use a function or variable even before it is written in the code. Why It Happens: JavaScript interpreter reads the entire code first and sets up memory for all variables and functions. That why you can access them before their actual line of code appears. Uses: 1) Helps in calling functions before they are defined. 2) Makes code organization flexible. Problems: 1) Can cause confusion for beginners. 2) Variables declared with var become undefined if used before declaration. 3) let and const declarations cause an error if used too early #JavaScriptMagic #CodingTips #LearnJS #FrontendFun #ProgrammingLife #JSBeginners #WebDev #TypeScript #CodeSmart #DeveloperCommunity
To view or add a comment, sign in
-
🚀 JavaScript Trick of the Day! const a = { valueOf: () => 2 * 1 }; console.log(2 + a); // What’s the output? 💡 Answer: 4 Why? When using +, JavaScript tries to convert objects to a primitive. Since the object has a custom valueOf(), JS uses that → returns 2. So: 2 + 2 = 4. 🧠 A reminder that JavaScript type coercion can be surprising — but powerful when understood! #JavaScript #WebDevelopment #CodingTips #100DaysOfCode #JSInterviewPrep
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