🚀 Implemented Promise.all & Promise.allSettled from Scratch (Polyfills) Recently, I deep-dived into JavaScript internals and implemented custom polyfills for: ✅ Promise.all ✅ Promise.allSettled Why? Because understanding how these combinators work internally separates surface-level JS knowledge from real engine-level understanding. 🔥 Key Learnings 🔹 1. Order Preservation is Critical Even if promises resolve at different times, results must match the input order. Using valueArray[index] = result ensures correct alignment. 🔹 2. Immediate Rejection in Promise.all If any promise rejects: The entire Promise.all should reject immediately. Remaining promises still execute, but the outer promise is already settled. 🔹 3. Promise.allSettled Never Rejects Unlike Promise.all, allSettled: Waits for all promises Returns structured results: { status: "fulfilled", value } { status: "rejected", reason } 🔹 4. Handling Edge Cases Empty array → resolve immediately Mixed resolved + rejected promises Maintaining parallel execution Avoiding race condition issues 💡 Why This Matters This isn’t just about writing code that works. It’s about: Understanding async control flow Mastering the event loop mental model Writing spec-accurate implementations Thinking like a JavaScript engine These are exactly the kind of deeper JavaScript concepts discussed in high-level frontend interviews at strong product companies. 🧠 Takeaway If you can implement: Promise.all Promise.allSettled Correctly handling: Order Early rejection Edge cases Status formatting You’re no longer just using JavaScript. You’re understanding how it works under the hood. #JavaScript #FrontendDevelopment #AsyncJavaScript #Promises #WebDevelopment #InterviewPrep #SoftwareEngineering
Implementing Promise.all & Promise.allSettled from Scratch
More Relevant Posts
-
🚀 20 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 𝗧𝗵𝗮𝘁 𝗖𝗮𝗻 𝗛𝗲𝗹𝗽 𝗬𝗼𝘂 𝗖𝗿𝗮𝗰𝗸 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄𝘀 If you’re preparing for frontend roles, make sure you’re confident with these core JavaScript concepts: 1. What are higher-order functions in JavaScript, and can you give an example? 2. What is destructuring in JavaScript, and why is it useful? 3. What are template literals, and how do they improve string handling? 4. How does the spread operator (…) work? 5. What is the rest parameter, and how is it different from the arguments object? 6. What is the difference between an object and an array? 7. How do you properly clone an object or an array? 8. What do Object.keys(), Object.values(), and Object.entries() do? 9. How does the map() method work, and when should you use it? 10. What is the difference between map() and forEach()? 11. What is event delegation, and why is it powerful? 12. What are JavaScript modules, and how do import/export work? 13. What is the prototype chain, and how does inheritance happen in JavaScript? 14. What is the difference between bind(), call(), and apply()? 15. How does JavaScript handle equality comparisons (== vs ===)? 16. What is the DOM, and how does JavaScript interact with it? 17. How do you prevent default behavior and stop event propagation? 18. What is the difference between synchronous and asynchronous code? 19. What is the difference between a native event object and a custom event? 20. How do you optimize performance in JavaScript applications? If you can clearly explain these concepts with examples, you’re in a strong position for most frontend interviews. #JavaScript #FrontendDevelopment #WebDevelopment #InterviewPreparation #ReactJS #SoftwareDevelopment
To view or add a comment, sign in
-
-
JavaScript Notes: From Fundamentals to Advanced Concepts (Interview & Production Ready) These JavaScript notes are a structured, practical, and interview-oriented collection of concepts that every frontend and full-stack developer must understand deeply, not just memorize. Instead of surface-level definitions, these notes focus on how JavaScript actually works under the hood, why certain bugs occur, and how JS behaviour affects React performance, scalability, and real-world production applications. The content is built from: Real interview questions Debugging experience from real projects Common mistakes developers make even after years of experience What these notes cover JavaScript Fundamentals Execution context & call stack Scope, lexical environment & scope chain var, let, const (memory & hoisting differences) Hoisting explained with execution flow Core JavaScript Concepts this keyword (implicit, explicit, arrow functions) Closures (memory behaviour & real use cases) Prototypes & prototypal inheritance Shallow vs deep copy Reference vs value Asynchronous JavaScript Callbacks & callback hell Promises (microtask queue behaviour) Async/Await (what actually pauses execution) Event loop, microtasks vs macrotasks Real execution order questions asked in interviews Advanced & Interview-Critical Topics Debouncing & throttling Currying & function composition Polyfills (map, filter, reduce, bind) Equality operators (== vs ===) Memory leaks & garbage collection basics JavaScript for React Developers Closures inside hooks Reference equality & re-renders Immutability & state updates Async state behaviour Performance pitfalls caused by JS misunderstandings #ReactJS #JavaScriptForReact #FrontendPerformance #Hooks #WebDevelopers
To view or add a comment, sign in
-
What do you think will be the output of these expressions in javascript? {} + [] [] + {} {} + {} [] + [] At first glance, most developers assume JavaScript will treat these as normal object or array operations. But the real reason behind the output is type coercion and how JavaScript converts objects and arrays into primitive values when using the + operator. When the + operator is used with objects or arrays, JavaScript tries to convert them into primitive values (usually strings). An empty array [] becomes an empty string "" An object {} becomes "[object Object]" After this conversion, the + operator performs string concatenation. So the expressions effectively become: "[object Object]" + "" "" + "[object Object]" "[object Object]" + "[object Object]" "" + "" Understanding this behavior is important because JavaScript’s implicit type coercion can sometimes lead to unexpected results in real-world applications. A simple rule to remember: {} → "[object Object]" [] → "" Once you remember this conversion, these puzzles become much easier to reason about. For more insightful content checkout below: 🟦 𝑳𝒊𝒏𝒌𝒆𝒅𝑰𝒏 - https://lnkd.in/dwi3tV83 ⬛ 𝑮𝒊𝒕𝑯𝒖𝒃 - https://lnkd.in/dkW958Tj 🟥 𝒀𝒐𝒖𝑻𝒖𝒃𝒆 - https://lnkd.in/dDig2j75 or Priya Frontend Vlogz 🔷 𝐓𝐰𝐢𝐭𝐭𝐞𝐫 - https://lnkd.in/dyfEuJNt #frontend #javascript #react #reactjs #html #css #typescript #es6 #interviewquestions #interview #interviewpreparation
To view or add a comment, sign in
-
-
JavaScript is easy to start with - but surprisingly hard to truly understand. Many developers can write JavaScript. Far fewer understand what actually happens under the hood. And that difference is often what separates someone who just writes code from someone who can truly reason about it. Here are a few core JavaScript internals every developer should understand: 🔹 Execution Context & Call Stack JavaScript code runs inside execution contexts. Each function call creates a new execution context that gets pushed onto the call stack. Understanding this explains recursion behavior, stack overflows, and how scope is resolved during execution. 🔹 Event Loop JavaScript itself runs on a single thread, but asynchronous behavior is enabled by the runtime (e.g., the browser or Node.js). The event loop coordinates the call stack, task queue (macrotasks), and microtask queue (Promises, queueMicrotask, etc.) to decide when callbacks are executed. 🔹 Closures A closure occurs when a function retains access to variables from its lexical scope, even after the outer function has finished executing. Closures are widely used for encapsulation, stateful functions, and many library/framework patterns. 🔹 Prototypes & Inheritance JavaScript uses prototype-based inheritance. Objects can inherit properties and methods through the prototype chain. Even modern "class" syntax is syntactic sugar on top of this mechanism. 🔹 Hoisting During the creation phase of an execution context, declarations are processed before code execution. Function declarations are fully hoisted, while "var" is hoisted but initialized with "undefined". "let" and "const" are hoisted but remain in the Temporal Dead Zone until initialization. 🔹 The "this" keyword "this" is determined by how a function is called, not where it is defined. Its value depends on the call-site (method call, constructor call, explicit binding with "call/apply/bind", or arrow functions which capture "this" lexically). Once you understand these mechanics, JavaScript stops feeling "magical" - and becomes far more predictable. What JavaScript concept took you the longest to fully understand? #javascript #webdevelopment #softwareengineering #frontend
To view or add a comment, sign in
-
-
Event Loop Deep Dive The Heartbeat of JavaScript JavaScript looks simple on the surface… but behind the scenes, something powerful is running everything the Event Loop. If you truly understand this, you move from coder pro developer What is the Event Loop? The Event Loop is a mechanism that allows JavaScript to handle multiple tasks without being multi-threaded. It decides what runs now and what waits. Core Components You Must Know Call Stack Where your code executes line by line Sync code runs here instantly Web APIs (Browser/Node) Handles async tasks like: setTimeout fetch API DOM events Callback Queue (Task Queue) Stores callbacks from async operations Microtask Queue (VIP Queue) Higher priority than callback queue: Promises (.then, catch) MutationObserver Execution Flow (Simple Way) Code enters Call Stack Async tasks go to Web APIs When ready → move to Queue Event Loop checks: Is Call Stack empty? YES Execute from Microtask Queue first Then Callback Queue Golden Rule Microtasks ALWAYS run before Macrotasks Example: JavaScript Copy code console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Output: Copy code Start End Promise Timeout Why This Matters Fix async bugs Optimize performance Write non-blocking code Crack interviews easily Pro Tip If your app feels slow… It’s not JavaScript It’s your understanding of the Event Loop Final Thought Mastering the Event Loop is like unlocking the brain of JavaScript. Once you get it… You don’t just write code you control execution #JavaScript #WebDevelopment #EventLoop #AsyncJS #CodingLife #FrontendDev
To view or add a comment, sign in
-
-
🔥 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
-
-
Day 15: The this Keyword in JavaScript this is one of the most misunderstood concepts in JavaScript 🤯 Its value depends on HOW a function is called, not where it is written. 🔹 1️⃣ Global Scope console.log(this); 👉 In browser → window 👉 In Node → {} (module.exports) 🔹 2️⃣ Inside a Regular Function function show() { console.log(this); } show(); 👉 In non-strict mode → window 👉 In strict mode → undefined 🔹 3️⃣ Inside an Object Method const user = { name: "Shiv", greet: function() { console.log(this.name); } }; user.greet(); 👉 this refers to the object → user 🔹 4️⃣ Arrow Function const user = { name: "Shiv", greet: () => { console.log(this); } }; user.greet(); 👉 Arrow functions do NOT have their own this 👉 They inherit from their lexical scope 🔥 Key Rule this depends on: ✔️ How the function is called ✔️ Whether it’s arrow or regular ✔️ Strict mode 🧠 Why Important? ✔️ Core interview topic ✔️ Important in React ✔️ Needed for call, apply, bind #JavaScript #thisKeyword #Frontend #Webdevelopment #learnInPublic
To view or add a comment, sign in
-
🚀 Day 77 — Microtask Queue vs Callback Queue in JavaScript Today I learned how JavaScript prioritizes asynchronous tasks using Microtask Queue and Callback Queue. Understanding this helped me finally understand execution order in async JavaScript. 🧠 The Hidden Queues Behind Async JavaScript When asynchronous tasks finish execution, they don’t directly enter the Call Stack. Instead, they wait inside queues. ✅ Callback Queue (Macrotask Queue) Handles: setTimeout setInterval DOM events ✅ Microtask Queue Handles: Promises (.then, .catch) queueMicrotask MutationObserver --- 🔍 Example console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); --- ⚙️ Output Start End Promise Timeout --- 🤯 Why This Happens? Execution order: 1️⃣ Synchronous code runs first 2️⃣ Microtask Queue executes next 3️⃣ Callback Queue executes last 👉 Microtasks always get higher priority than callbacks. --- 📌 Key Learning Even if setTimeout has 0ms delay, Promises execute before it because Microtask Queue is processed first. Understanding this explains many async bugs and unexpected outputs. --- JavaScript execution feels much clearer as I go deeper into how things work internally. --- #Day77 #JavaScript #EventLoop #AsyncJavaScript #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
💡 Interesting JavaScript Question I Faced Recently (2+ Years Experience Level) Recently I came across a practical JavaScript question that focused on understanding how Promises work internally. 📌 The Task Create a Promise when the JavaScript file loads. The Promise should remain in the pending state until the user clicks a button. Two buttons should determine the outcome: • Resolve button → resolves the Promise • Reject button → rejects the Promise The implementation had to be done using Vanilla JavaScript and HTML only. 🎯 Approach Create a Promise immediately when the script loads. Attach event listeners to two buttons. Call resolve() when the resolve button is clicked. Call reject() when the reject button is clicked. Handle the result using .then() and .catch(). ⚡ Key Learning This small exercise highlights the core behavior of a Promise: • A Promise starts in pending state • It transitions to resolved or rejected once • The state cannot change again after settlement Questions like these test JavaScript fundamentals and event-driven async behaviour, which are very important in frontend interviews. Curious to know - how would you extend this example? Maybe with async/await, UI feedback, or disabling buttons after resolution? #javascript #frontenddevelopment #webdevelopment #promises #learning #interviewquestions
To view or add a comment, sign in
-
-
Day 13: Promise APIs in JavaScript (Promise.all, race, allSettled, any) If you really want to master async JavaScript, you must understand the Promise APIs 💡 JavaScript gives us powerful methods to handle multiple promises. 🔹 1️⃣ Promise.all() 👉 Waits for all promises to succeed 👉 Fails immediately if any one fails Promise.all([api1(), api2(), api3()]) .then(results => console.log(results)) .catch(error => console.log(error)); ✅ Best when all results are required ❌ One failure = everything fails 🔹 2️⃣ Promise.race() 👉 Returns the first promise that settles (resolve or reject) Promise.race([api1(), api2(), api3()]) .then(result => console.log(result)) .catch(error => console.log(error)); ✅ Useful for timeout logic 🔹 3️⃣ Promise.allSettled() 👉 Waits for all promises 👉 Returns status of each (fulfilled/rejected) Promise.allSettled([api1(), api2()]) .then(results => console.log(results)); ✅ Useful when you want all results, even if some fail 🔹 4️⃣ Promise.any() 👉 Returns the first fulfilled promise 👉 Ignores rejected ones Promise.any([api1(), api2()]) .then(result => console.log(result)) .catch(error => console.log(error)); ✅ Best when you only need one successful response 🔥 Quick Summary • Promise.all → All must succeed • Promise.race → First settled wins • Promise.allSettled → Get all results • Promise.any → First success wins 🧠 Why Important? ✔️ Used in real-world APIs ✔️ Common frontend interview question ✔️ Helps optimize async performance #JavaScript #Promises #AsyncJavaScript #webdevelopment #LearnInPublic
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
👏