🚨 A small JavaScript Promise detail that many developers misunderstand While studying the JavaScript Event Loop, I realized something interesting about Promises. Many developers assume that creating a Promise automatically pushes it into the Microtask Queue. But that’s not what actually happens. Let’s look at a simple example. const promise = new Promise((resolve, reject) => { console.log("Executor running"); resolve("Done"); }); When this Promise is created, the function inside the constructor (called the executor function) runs immediately and synchronously inside the Call Stack. So at this point, nothing is added to the Microtask Queue. The Microtask Queue only becomes relevant when we consume the Promise using: • .then() • .catch() • .finally() Example: Promise.resolve("Hello") .then((data) => { console.log(data); }); Here, the callback inside .then() is scheduled in the Microtask Queue. This means it will execute after the current Call Stack becomes empty but before any Macrotasks run. Let’s see a small example that shows this behavior clearly. console.log("Start") Promise.resolve().then(() => { console.log("Promise") }) setTimeout(() => { console.log("Timeout") }, 0) console.log("End") Output: Start End Promise Timeout Why does this happen? Because JavaScript processes tasks in the following order: 1️⃣ Call Stack (synchronous code) 2️⃣ Microtask Queue (Promises) 3️⃣ Macrotask Queue (setTimeout, setInterval) Understanding this flow makes asynchronous JavaScript much easier to reason about and debug. To explore this concept better, I’m currently planning to build a small Event Loop Visualizer that will show: • Call Stack • Microtask Queue • Macrotask Queue working together visually. Stay tuned for that 🚀 Sarthak Sharma Devendra Dhote Ritik Rajput Sheryians Coding School Community #JavaScript #AsyncJavaScript #EventLoop #WebDevelopment #FrontendDevelopment#SheryiansCodingSchool
JavaScript Promises and the Event Loop Explained
More Relevant Posts
-
Frontend Learning — Understanding Event Loop in JavaScript JavaScript is single-threaded, but still handles async tasks like APIs, timers, and promises smoothly — thanks to the Event Loop. -> So how does it actually work? 1️⃣ Call Stack – Executes synchronous code line by line 2️⃣ Web APIs – Handles async tasks (setTimeout, fetch, etc.) 3️⃣ Callback Queue – Stores callbacks from async operations 4️⃣ Microtask Queue – Stores promises (.then, catch) 5️⃣ Event Loop – Decides what runs next -> Execution Priority: First → Call Stack Then → Microtasks (Promises) Then → Macrotasks (setTimeout, setInterval) -> Why this matters: Understanding this helps you debug async issues, optimize performance, and write predictable code. -> Key Takeaway: Promises always execute before setTimeout (even with 0 delay). #JavaScript #FrontendDevelopment #WebDevelopment #AsyncJavaScript #EventLoop #CodingTips #LearnInPublic #DeveloperJourney
To view or add a comment, sign in
-
-
While writing some JavaScript logic recently, I noticed I was getting stuck on simple decision-making in code. Nothing complex just if-else and switch. But it made me realize I was writing conditions without really thinking through the flow properly. So I went back, broke it down, and tried to understand how control flow actually works. That led me to write this blog. If you’re learning JavaScript or revisiting the basics, this might help: https://lnkd.in/dNjZqNuS #JavaScript #LearningInPublic #WebDevelopment #BuildInPublic #chaicode #chaiaurcode
To view or add a comment, sign in
-
🚀 Day 6 of My JavaScript Journey Today was all about mastering Strings & Date Object in JavaScript — and honestly, it made me realize how powerful these basics really are 🔥 Here’s what I learned 👇 📌 Strings in JavaScript Different ways to create strings ("", '', and backticks ` `) Why backticks (template literals) are modern & super useful 💡 Finding string length using .length Accessing characters using index 📌 Important Concept Strings are immutable → original value can’t be changed ⚠️ 📌 String Methods Convert text: .toUpperCase() .toLowerCase() Search inside strings: .includes(), .indexOf() Extract parts: .slice() (supports negative index 🔥) .substring() Modify strings: .replace() .trim() Convert string to array: .split() 📌 Concatenation Combine strings using + Mixing numbers with strings → automatic type conversion 🤯 📌 Date Object (Real Game Changer 🕒) Getting current date & time Understanding UTC vs Local Time Formatting date (ISO & local formats) Extracting parts like year, month, day Creating custom dates 📌 Advanced Concepts Date.now() → gives milliseconds since Epoch (Jan 1, 1970) ⏳ Importance of UTC & Epoch Time in real-world apps Browser automatically converts UTC → Local Time 🌍 💡 Big Learning: Even basic things like strings & dates have deep concepts that are used in real-world applications like chat apps, logs, scheduling systems, etc. Consistency is the key 🔑 Day by day, getting closer to becoming a better developer 💻🔥 #JavaScript #WebDevelopment #MERNStack #CodingJourney #Day6 #Learning #Developers
To view or add a comment, sign in
-
-
🚀 5 Advanced JavaScript Concepts Every Developer Should Understand As you move beyond the basics in JavaScript, understanding some deeper concepts becomes very important. These concepts help you write better code, debug complex issues, and understand how JavaScript actually works behind the scenes. Here are 5 advanced JavaScript concepts every developer should know. 1️⃣ Closures Closures occur when a function remembers variables from its outer scope even after that outer function has finished executing. They are commonly used in callbacks, event handlers, and data privacy patterns. 2️⃣ The Event Loop JavaScript is single threaded, but it can still handle asynchronous operations through the Event Loop. Understanding the call stack, task queue, and microtask queue helps explain how asynchronous code runs. 3️⃣ Debouncing and Throttling These techniques control how often a function executes. They are extremely useful when handling events like scrolling, resizing, or search input to improve performance. 4️⃣ Prototypal Inheritance Unlike many other languages, JavaScript uses prototypes to enable inheritance. Understanding prototypes helps you understand how objects share properties and methods. 5️⃣ Currying Currying is a functional programming technique where a function takes multiple arguments one at a time. It allows you to create more reusable and flexible functions. Mastering concepts like these helps developers move from simply writing JavaScript to truly understanding how it works. Which JavaScript concept took you the longest to understand? #JavaScript #WebDevelopment #Programming #Developers #FrontendDeveloper
To view or add a comment, sign in
-
-
🚨 JavaScript Objects looked simple… until I explored what’s actually happening behind the scenes. When I first started learning JavaScript, objects felt very straightforward — just {} and some key-value pairs. But today I spent time digging deeper into how JavaScript objects actually work, and I realized there's a lot more happening internally. Here are a few concepts that really stood out to me while learning 👇 💡 Object Literals – the simplest way to create objects let user = { name: "Pradeep", age: 21 }; 🧱 Constructor Functions (ES5) – useful when you want to create multiple objects with the same structure function User(name) { this.name = name; } 🔍 this Keyword – it refers to the object that is calling the function, which makes context very important in JavaScript. 🧬 Prototype – methods added to the prototype are shared across all instances created from the constructor. This helps save memory and avoid repeating the same functions for every object. ⚙️ Object.create() – allows you to create a new object using another object as its prototype. 🧠 Shallow Copy vs Deep Copy – something that confused me at first. Shallow copy: let copy = { ...obj }; Deep copy: let copy = JSON.parse(JSON.stringify(obj)); ⚠️ Important insight: A shallow copy only copies the first level. If the object contains nested objects, changes can still affect the original. Learning this made me realize that JavaScript objects are powered by a powerful prototype system, not just simple key-value storage. Still learning and exploring JavaScript fundamentals every day. 🚀 💬 What JavaScript concept took you the longest to understand? #javascript #webdevelopment #frontenddevelopment #codingjourney #softwaredevelopment #developers #programming #100daysofcode
To view or add a comment, sign in
-
🚀 Understanding the JavaScript Event Loop 🚀 Today I explored one of the most important concepts in JavaScript — the Event Loop. JavaScript is known as a single-threaded language, which means it can execute only one task at a time. But modern web applications perform many operations simultaneously, such as API calls, timers, and user interactions. This is where the Event Loop makes JavaScript powerful. 🔍 What’s Involved? The JavaScript runtime manages asynchronous operations using a few key components: • Call Stack – Executes synchronous code line by line • Web APIs – Handles asynchronous operations like setTimeout, DOM events, and API requests • Callback Queue – Stores callback functions waiting to be executed • Event Loop – Continuously checks if the call stack is empty and moves tasks from the queue to the stack Example: console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 0); console.log("End"); Output: Start End Async Task Even though the delay is 0, the callback runs later because it first goes to the callback queue, and the event loop executes it only when the call stack becomes empty. Why It Matters: ✅ Handles Asynchronous Operations Efficiently ✅ Improves Application Performance ✅ Prevents Blocking of the Main Thread ✅ Essential for APIs, Timers, and Event Handling ✅ Core concept for Node.js and modern web applications Understanding the Event Loop helps developers write better asynchronous code and debug complex JavaScript behavior. Currently exploring deeper JavaScript concepts step by step to strengthen my development skills. 💻 #JavaScript #EventLoop #AsyncJavaScript #WebDevelopment #Developers #Programming #LearningJourney
To view or add a comment, sign in
-
🚀 Day 5 / 100 — JavaScript Concepts That Every Developer Should Understand #100DaysOfCode Today I revised two very important JavaScript concepts that often come up in interviews and real-world debugging: 🔐 1. Closures A closure happens when a function remembers variables from its outer scope even after the outer function has finished executing. In simple words: A function carries its environment with it. Example: function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 Why this works: Even though outer() has finished running, inner() still remembers the variable count. 📌 Common use cases • Data privacy • Function factories • React hooks • Event handlers 🧠 2. Call Stack The call stack is how JavaScript keeps track of function execution. It works like a stack (Last In, First Out). Whenever a function runs: 1️⃣ It gets pushed onto the stack 2️⃣ When it finishes, it gets popped off Example: function one() { two(); } function two() { three(); } function three() { console.log("Hello from the call stack"); } one(); Execution order in the call stack: Call Stack three() two() one() global() Then it unwinds after execution. 📌 Understanding the call stack helps with: • Debugging errors • Understanding recursion • Avoiding stack overflow 💡 Key realization today: JavaScript is single-threaded, and concepts like closures + call stack explain a lot about how the language actually works behind the scenes. Mastering these fundamentals makes async JS, promises, and the event loop much easier later. 🔥 Day 5 completed. 95 days to go. If you're also learning to code, comment “100” and let’s stay consistent together 🤝 #javascript #100daysofcode #webdevelopment #coding #developers #programming #learninpublic #buildinpublic #SheryiansCodingSchool #Sheryians
To view or add a comment, sign in
-
-
🚀 JavaScript Concepts Series – Day 9 / 30 📌 Promises & Async/Await in JavaScript 👀 Let's Revise the Basics 🧐 Understanding Promises & Async/Await is key to handling asynchronous operations cleanly and efficiently. They help you write non-blocking code without callback hell. 🔹 Promises A Promise represents a value that may be available now, later, or never States: Pending → Resolved → Rejected const promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Done"), 1000); }); promise.then(res => console.log(res)) .catch(err => console.log(err)); 🔹 Async/Await Syntactic sugar over promises Makes async code look like synchronous code async function fetchData() { try { const res = await promise; console.log(res); } catch (err) { console.log(err); } } 🔹 Why Use It? Cleaner and readable code Better error handling with try...catch Avoids callback hell 💡 Key Insight Promise → Handles async operations async/await → Makes it readable await → Pauses execution (non-blocking) Mastering this helps you work with APIs, handle data, and build real-world applications efficiently. More JavaScript concepts coming soon. 🚀 #javascript #js #webdevelopment #frontenddeveloper #coding #programming #developers #softwaredeveloper #learnjavascript #javascriptdeveloper #codinglife #devcommunity #webdev #reactjs #mernstack #codingjourney #codeeveryday #developerlife #100daysofcode #techlearning #asyncjs #promises
To view or add a comment, sign in
-
-
🚨 Most developers think they understand JavaScript Arrays… until they see these results. 🤯 Today during my JavaScript practice, I realized something important: 👉 JavaScript arrays are easy to use, but tricky to truly understand. Some small examples can completely change how you think about the language. 🔥 1. map() vs forEach() let arr = [1,2,3]; let a = arr.forEach(x => x * 2); let b = arr.map(x => x * 2); console.log(a); // undefined console.log(b); // [2,4,6] ⚡ forEach() executes logic but returns nothing ⚡ map() returns a new transformed array 🔥 2. The famous sort() trap [1,2,10].sort() Result: [1,10,2] Why? 🤔 Because JavaScript sorts values as strings by default, not numbers. Correct way: [1,2,10].sort((a,b)=>a-b) 🔥 3. Removing duplicates from an array let arr = [1,2,3,2,1]; let unique = arr.filter((x,i,a) => a.indexOf(x) === i); console.log(unique); // [1,2,3] 🔥 4. Getting duplicate values let duplicates = arr.filter((x,i,a) => a.indexOf(x) !== i); Output: [2,1] 💡 Big learning from today: JavaScript isn’t just about writing code. It’s about understanding how the language actually behaves under the hood. Small hidden behaviors can make a huge difference in interviews and real-world projects. 📚 Array methods I practiced today ✔ push ✔ pop ✔ shift ✔ unshift ✔ splice ✔ slice ✔ map ✔ filter ✔ reduce ✔ find ✔ findIndex ✔ includes ✔ indexOf ✔ sort ✔ forEach ✔ every Still learning. Still improving. 🚀 If you're learning JavaScript too, which array method confused you the most when you started? 👇 #javascript #webdevelopment #frontenddevelopment #programming #coding #softwaredeveloper #developers #techcommunity #100daysofcode #learninpublic #js #codingjourney #webdev #developerlife
To view or add a comment, sign in
-
Revisiting the JavaScript Event Loop Sometimes going back to fundamentals is just as important as building new things. Today I revisited how the JavaScript Event Loop works a concept we use daily but don’t always think about deeply. A quick refresher: • JavaScript runs on a single-threaded call stack • Async operations are handled outside the main thread • Completed tasks move into queues • The Event Loop executes them when the call stack is empty One thing worth remembering: Promises (microtasks) are always prioritized over callbacks like setTimeout Even after working with async code regularly, understanding why things execute in a certain order is what really helps in debugging and writing better code. 📖 Article: https://lnkd.in/dnYVfHrQ #JavaScript #NodeJS #EventLoop #AsyncProgramming #BackendDevelopment
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