🚨 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 (𝗢𝘂𝘁𝗽𝘂𝘁 𝗕𝗮𝘀𝗲𝗱) Many JavaScript interviews don’t test how much you know… They test how deeply you understand the language. Here are 3 small JavaScript snippets that often confuse developers in interviews 👇 🧠 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟭: 𝘃𝗮𝗿 𝘃𝘀 𝗹𝗲𝘁 𝗶𝗻 𝗹𝗼𝗼𝗽𝘀 𝑓𝑜𝑟 (𝑣𝑎𝑟 𝑖 = 0; 𝑖 < 3; 𝑖++) { 𝑠𝑒𝑡𝑇𝑖𝑚𝑒𝑜𝑢𝑡(() => 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑖), 1000); } 𝗢𝘂𝘁𝗽𝘂𝘁: 3, 3, 3 💡 𝗪𝗵𝘆? var is 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝘀𝗰𝗼𝗽𝗲𝗱, not block scoped. All callbacks share the same i variable. By the time setTimeout runs, the loop has finished and i = 3. ✔️ 𝗙𝗶𝘅 𝘂𝘀𝗶𝗻𝗴 𝗹𝗲𝘁 for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } Output: 0, 1 ,2 Because let creates a new binding for each iteration. 🧠 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟮: 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝘆𝗽𝗲 𝗖𝗼𝗲𝗿𝗰𝗶𝗼𝗻 console.log("5" - 3); console.log("5" + 3); console.log(true + true); Output: 2, 53, 2 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 JavaScript performs 𝗶𝗺𝗽𝗹𝗶𝗰𝗶𝘁 𝘁𝘆𝗽𝗲 𝗰𝗼𝗲𝗿𝗰𝗶𝗼𝗻. "5" - 3 → number conversion → 5 - 3 = 2 "5" + 3 → string concatenation → "53" true + true → 1 + 1 = 2 👉 The + operator prefers string concatenation, while other operators trigger numeric conversion. 🧠 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟯: 𝘁𝗵𝗶𝘀 𝗶𝗻𝘀𝗶𝗱𝗲 𝗮𝗿𝗿𝗼𝘄 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 const obj = { name: "Shubham", greet: function() { setTimeout(() => { console.log(this.name); }, 1000); } }; obj.greet(); Output: Shubham 💡 𝗪𝗵𝘆? Arrow functions do not have their own this. They inherit this from the surrounding scope. Here, this refers to obj. 💬 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗶𝗽 Most JavaScript interview questions revolve around: • Scope • Closures • this keyword • Type coercion • Event loop Mastering these concepts makes 𝗝𝗦 𝗶𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗾𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 𝗺𝘂𝗰𝗵 𝗲𝗮𝘀𝗶𝗲𝗿. 🔥 𝗤𝘂𝗶𝗰𝗸 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 What will be the output of this? console.log([] + []); console.log([] + {}); console.log({} + []); Write your answers in the comments 👇 ♻️ If you found this helpful, repost to help other developers preparing for JavaScript interviews. 📌 Follow Shubham Kumar Raj for more such content😊 #javascript #webdevelopment #frontenddeveloper #codinginterview #softwaredevelopment #learnjavascript #100daysofcode #hiring
JavaScript Interview Questions and Answers
More Relevant Posts
-
🚨 I recently went through a JavaScript interview and they asked some very tricky questions. Honestly, these were not the usual “What is closure?” or “What is hoisting?” questions. They were designed to test how deeply you understand JavaScript execution, async behavior, and edge cases. If you’re preparing for Frontend / React interviews, don’t miss these questions. 👇 🧠 1️⃣ Predict the Output console.log([] + []); console.log([] + {}); console.log({} + []); console.log({} + {}); What exactly gets printed and why does JavaScript behave like this? ⚡ 2️⃣ Event Loop Deep Dive console.log("start"); setTimeout(() => console.log("timeout")); Promise.resolve().then(() => console.log("promise")); queueMicrotask(() => console.log("microtask")); console.log("end"); 👉 What is the exact output order? 🔥 3️⃣ Closures + Loop Trap for (var i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 100); } What will be printed and why does this happen? 🧩 4️⃣ this Binding Confusion const obj = { value: 10, getValue() { return this.value; } }; const getValue = obj.getValue; console.log(getValue()); What will this print? ⚠️ 5️⃣ Object Reference Trap const a = { name: "JS" }; const b = a; b.name = "React"; console.log(a.name); Why does this happen? 🧪 6️⃣ Array Mutation Trick const arr = [1,2,3]; arr[10] = 99; console.log(arr.length); console.log(arr); What does the array actually look like? 🧠 7️⃣ Destructuring Edge Case const obj = { a: 1, b: 2 }; const { a, ...rest } = obj; rest.b = 5; console.log(obj.b); Does the original object change? ⚡ 8️⃣ Promise Chain Trap Promise.resolve(1) .then(x => x + 1) .then(x => { throw new Error("boom"); }) .catch(() => 10) .then(x => console.log(x)); What is the final output? 🔥 9️⃣ typeof Weirdness console.log(typeof NaN); console.log(typeof null); console.log(typeof []); Why do these results exist in JavaScript? 🧨 🔟 Implicit Type Coercion console.log("5" - 3); console.log("5" + 3); console.log(true + false); console.log([] == false); Explain how JavaScript converts the types internally. 💡 Principal Engineer Advice In interviews, they’re not testing if you memorized JavaScript. They are testing if you understand: ⚡ Execution Context ⚡ Event Loop ⚡ Closures ⚡ Type Coercion ⚡ Object References Master these and JavaScript interviews become much easier. 🔥 I’ll keep posting tricky Frontend / React interview questions daily to help juniors crack interviews. #javascript #frontend #reactjs #webdevelopment #frontendengineer #codinginterview
To view or add a comment, sign in
-
-
Here’s something commonly asked in JavaScript interviews 👇 Shallow vs Deep Copy Shallow Copy Copies only top-level properties. Nested objects are copied by reference, so changes affect the original. 👉 Ways: Object.assign(), spread (...), Array.from() Deep Copy Creates a fully independent copy, including nested objects. A common approach: JSON.parse(JSON.stringify(obj)) ⚠️ Catch with JSON.stringify() It fails for: • functions (removed) • undefined (removed or become null if arr) • Date (becomes string) • NaN / Infinity (become null) • Map, Set, RegExp (structure lost) • circular references (error) ✅ Better approach const newObj = structuredClone(obj) ✔ Handles most cases (Map, Set, Date, circular refs) ❌ Still can’t clone functions 🔥 Advanced: Custom Deep Clone If you also want to handle functions, you need a custom solution: function deepClone(obj) { if (obj === null || typeof obj !== "object") return obj; if (obj instanceof Date) return new Date(obj); if (obj instanceof RegExp) return new RegExp(obj); if (typeof obj === "function") return obj.bind({}); if (Array.isArray(obj)) { return obj.map(item => deepClone(item)); } const cloned = {}; for (let key in obj) { cloned[key] = deepClone(obj[key]); } return cloned; } ⚠️ Note: • Functions are copied by reference (true cloning isn’t really possible) 💡 Takeaway • Use shallow copy for simple cases • Use structuredClone() for most real scenarios • Use custom clone only when you need full control Don't forget to follow Mohit Sharma 🚀 for more. #JavaScript #Frontend #WebDevelopment #InterviewPrep #ReactJS
To view or add a comment, sign in
-
💡 JavaScript IIFE (Immediately Invoked Function Expression) and Interview Classic: The setTimeout + var Trap Ever seen this weird-looking function? 👇 (function() { console.log("Hello World"); })(); 🤔 Looks different, right? 🧠 What is an IIFE? 👉 An IIFE (Immediately Invoked Function Expression) is a function that: ✔️ Is defined ✔️ And executed immediately No need to call it separately! 🔍 How does it work? (function(name) { console.log("Hello " + name); })("Javascript"); 👉 Output: Hello Javascript 🚀 Why do we use IIFE? 🔒 1. Creates a private scope Variables inside it cannot be accessed outside (function() { var secret = "hidden"; })(); ❌ secret is not accessible outside 🌍 2. Avoids global scope pollution Keeps your code clean and prevents conflicts. ⚡ 3. Helps with closures (classic interview use-case) This is one of the most famous questions asked in interviews 👇 for (var i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } 🤔 What will be the output? 👉 Most people expect: 0 1 2 3 4 ❌ But the actual output is: 5 5 5 5 5 🧠 What’s happening here? 🔹 var is function-scoped, not block-scoped 🔹 The loop finishes execution first → i becomes 5 🔹 setTimeout runs later (asynchronously) 🔹 All callbacks share the same reference of i 👉 So every console.log prints 5 ✅ How to fix it? 🔹a) Using let (block scope): for (let i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔️ Output: 0 1 2 3 4 🔹b) Using Closure (if you must use var): for (var i = 0; i < 5; i++) { (function(i) { setTimeout(() => { console.log(i); }, 1000); })(i); } What is this (function(i) { ... })(i)? 👉 This is an Immediately Invoked Function Expression (IIFE) (It runs immediately after being defined) So for each loop iteration: 🔹A new function is created 🔹It gets its own copy of i as a parameter 👉How closure helps here Inside the loop: First iteration → i = 0 → function runs with i = 0 → setTimeout remembers this i Second iteration → i = 1 → new function with i = 1 → new closure created 👉 This happens for all iterations So instead of sharing one i, we now have 5 different i values stored separately Final result After 1 second: 0 1 2 3 4 ✅ Each setTimeout prints its own preserved value 🔥 Simple analogy Think of it like: ❌ Without closure → 5 people sharing one notebook ✅ With closure → each person gets their own notebook 🚀 Key takeaway 👉 Closures allow functions to remember the variables from their scope 👉 IIFE creates a new scope for each iteration 👉 That’s why this fixes the var problem #JavaScript #CodingInterview #FrontendDevelopment #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
🚀 Got a frontend interview coming up? Screenshot this. 📸 Here are the JavaScript topics that come up again and again in interviews. ――――――――――――――――――――――― 1️⃣ Core JavaScript Basics → Data types and comparisons → Truthy vs falsy values → Difference between == and === → Implicit vs explicit type coercion → Object references vs primitive values A classic trap: two objects with the same values are NOT equal in JavaScript because objects are compared by reference. ――――――――――――――――――――――― 2️⃣ Scope & Execution Context → Closures and lexical scope → Hoisting and the Temporal Dead Zone → The this keyword (arrow vs regular functions) Very common question: “What will this console.log output?” Always trace the scope chain carefully. ――――――――――――――――――――――― 3️⃣ Functions & Useful Patterns → Spread vs rest operators → call, apply, and bind → Currying and partial application If you can clearly explain spread vs rest, you're already ahead of many candidates. ――――――――――――――――――――――― 4️⃣ Working with Arrays & Objects → map, filter, reduce → When NOT to use them → Shallow vs deep copying Understanding shallow copies can save you from some very confusing bugs. ――――――――――――――――――――――― 5️⃣ JavaScript Mechanics → Prototypal inheritance → typeof vs instanceof → Event loop and call stack → Microtasks vs macrotasks Drawing the event loop diagram once makes async questions much easier. ――――――――――――――――――――――― 6️⃣ Async JavaScript → Callbacks vs Promises vs async/await → Error handling with async/await → Debounce vs throttle → Event delegation and bubbling Many developers forget proper error handling in async code. ――――――――――――――――――――――― 7️⃣ Browser & Networking Basics → How browsers render HTML, CSS and JS → Critical rendering path → Reflow vs repaint → DNS lookup, TCP handshake, TLS → CORS and preflight requests These topics show up a lot in mid-senior frontend interviews. ――――――――――――――――――――――― 8️⃣ Performance & Caching → Preload, prefetch and lazy loading → Service workers → localStorage, sessionStorage and cookies Knowing when to use each storage option matters more than memorising definitions. ――――――――――――――――――――――― 9️⃣ Frontend Architecture & Accessibility → Responsive design and mobile-first layouts → Media queries and viewport units → Semantic HTML, ARIA roles, focus management Accessibility questions are becoming more common in interviews. ――――――――――――――――――――――― A tip that helped me: Pick one section a day Learn it deeply Build a small demo Explain it to someone else That’s how concepts actually stick. 💪 ――――――――――――――――――――――― Which area do you feel least confident about right now? 1️⃣ JavaScript fundamentals 2️⃣ Event loop & async 3️⃣ Browser internals 4️⃣ Performance Save this post so you can review it before your next interview 🔖 #JavaScript #FrontendDev #ReactJS #WebDev #InterviewPrep
To view or add a comment, sign in
-
👉 Solve below o/p based question if u beileve u have good understanding of JS Concepts" 🚨 I’ve appeared for multiple senior full-stack interviews recently, and "this" based quetion are must ask: 🚨 Senior-Level JavaScript Interviews Are NOT About Syntax — They’re About Understanding " .. .... ....... Here are a couple of commonly asked (and often confusing) questions 👇 🧠 Q1: Understanding this and Arrow Functions let obj = { name: "Ravi", fn: function () { console.log(this.name); }, arrFn: function () { (() => { console.log(this.name); })(); }, }; obj.fn(); obj.arrFn(); 💡 Concepts being tested: this binding in regular functions Lexical this in arrow functions Execution context Method invocation vs inner function 👉 Key Insight: Arrow functions don’t have their own this — they inherit it from their surrounding scope. ------------------------------------------------------------------- 🧠 Q2: Classes, Binding, and Function References class Person { age = 20; constructor(name) { this.name = name; this.func = this.func.bind(this); } func() { console.log(this.name); } arrowFunc = () => { console.log(this.name, this.age); }; } const person1 = new Person("Rahul"); person1.func(); person1.arrowFunc(); const copyFn = person1.func; copyFn(); 💡 Concepts being tested: Class fields & initialization Explicit binding using .bind(this) Difference between normal methods vs arrow functions in classes Function reference vs method call How "this" behaves when function is detached Do you really understand this? Can you predict output without running the code? 💬 If you’re preparing for senior roles, don’t just “know” JavaScript — understand its behavior in edge cases. #javascript #frontend #fullstack #webdevelopment #interviewprep #reactjs #nodejs #softwareengineering #codinginterview #jsconcepts
To view or add a comment, sign in
-
JavaScript Hoisting: The Interview Question That Tricks Everyone 🚀 Most developers think they know hoisting. Then the interviewer shows them tricky code. Here's your complete guide to mastering it. --- 🎯 The Definition Hoisting is JavaScript's behavior of moving declarations to the top of their scope during compilation. Key rule: Only declarations are hoisted, NOT initializations. --- 📊 The 3 Types (With Examples) 1. var – Hoisted & Initialized as undefined ```javascript console.log(name); // undefined (not error!) var name = "John"; // JS reads it as: // var name; → console.log(name); → name = "John"; ``` 2. let/const – Hoisted but NOT Initialized (TDZ) ```javascript console.log(age); // ❌ ReferenceError let age = 25; // Temporal Dead Zone – exists but inaccessible ``` 3. Function Declarations – Fully Hoisted ```javascript greet(); // ✅ "Hello" – works! function greet() { console.log("Hello"); } // Function expressions? NOT hoisted! ``` --- 🌍 Real-World Example The Bug That Wastes Hours: ```javascript function processOrders(orders) { for (var i = 0; i < orders.length; i++) { setTimeout(() => { console.log(orders[i]); // undefined × 3 }, 1000); } } // Why? var is function-scoped, hoisted to top. // Fix: Use let (block-scoped) or closure ``` The Solution: ```javascript function processOrders(orders) { for (let i = 0; i < orders.length; i++) { setTimeout(() => { console.log(orders[i]); // ✅ Works! }, 1000); } } ``` --- 💡 Senior-Level Insight "Hoisting explains why: · var causes unexpected bugs (always use let/const) · TDZ prevents accessing variables before declaration · Function hoisting enables clean code organization Modern JS best practice: Declare variables at the top. Use const by default, let when reassignment needed." --- 🎤 Interview Answer Structure Q: "Explain hoisting." "Hoisting is JavaScript's compilation-phase behavior where declarations are moved to the top. Function declarations are fully hoisted, var variables hoisted as undefined, while let/const are hoisted but stay in Temporal Dead Zone until execution. This is why we get undefined with var but ReferenceError with let when accessed early." --- 📝 Quick Cheat Sheet Type Hoisted Initial Value Access Before Declaration var ✅ undefined Returns undefined let ✅ Uninitialized ❌ ReferenceError (TDZ) const ✅ Uninitialized ❌ ReferenceError (TDZ) Function Dec ✅ Function itself ✅ Works fine --- 🚨 Common Interview Twist: ```javascript var a = 1; function test() { console.log(a); // undefined (not 1!) var a = 2; } test(); // Why? Inner var a is hoisted to top of function scope ``` --- Master hoisting = Master JavaScript execution. Found this helpful? ♻️ Share with your network. Follow me for more interview prep content! #JavaScript #CodingInterview #WebDevelopment #TechInterview #JSHoisting
To view or add a comment, sign in
-
𝗨𝗻𝗱𝗲𝗿𝗦𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗢𝗯𝗷𝗲𝗰𝗍 𝗞𝗲𝘆𝘀 𝗜𝗻 𝗝𝗮 v𝗮𝗦𝗰𝗿𝗶𝗽𝘁 You may encounter a tricky JavaScript question in an interview. Let's look at this example: let obj = {}; let a = { a: 10 }; let b = { b: 20 }; obj[a] = 10; obj[b] = 20; console.log(obj[a]); - Output: 20 In JavaScript, object keys can only be strings or symbols. When you use an object as a key, JavaScript converts it to a string using .toString(). So, obj[a] becomes obj["[object Object]"] and obj[b] becomes obj["[object Object]"]. The second assignment overwrites the first one. - Use Map when you want to use objects as keys. - Map preserves reference identity, so a and b are treated as different keys. - You can use Map when keys are objects or functions, or when you need preserved insertion order. You can also use JSON.stringify to convert objects to strings, but this method is fragile and depends on consistent serialization. Symbols are always unique, so you can use them as keys too. In JavaScript, object keys are always strings or symbols, even if you use numbers or booleans as keys. - Key differences between Object and Map: - Key types: Object uses strings and symbols, while Map can use any type. - Key conversion: Object converts keys to strings, while Map does not. - Order guarantee: Map preserves the order of insertion, while Object does not. - Performance: Map is better for dynamic use. - Iteration: Map has built-in methods for iteration, while Object does not. Source: https://lnkd.in/g8rG-wgV
To view or add a comment, sign in
-
🚀 JavaScript Hoisting — Explained with Tricky Examples + Interview Points Ever wondered how JavaScript runs your code before it even reaches certain lines? That’s where hoisting comes in 👇 🔹 What is Hoisting? Hoisting is JavaScript's default behavior of moving declarations (not initializations) to the top of their scope during the compilation phase. 🔹 Simple Example console.log(a); // undefined var a = 10; 👉 Behind the scenes: var a; console.log(a); a = 10; 🔹 Tricky Cases (Very Important!) 1️⃣ var vs let vs const console.log(a); // undefined var a = 5; console.log(b); // ❌ ReferenceError let b = 10; 👉 let and const are hoisted BUT not initialized → they stay in Temporal Dead Zone (TDZ) 2️⃣ Function Declaration vs Function Expression greet(); // ✅ Works function greet() { console.log("Hello"); } greet(); // ❌ Error var greet = function() { console.log("Hello"); }; 👉 Function declarations are fully hoisted 👉 Function expressions behave like variables 3️⃣ Variable + Function Same Name var x = 10; function x() { console.log("Hello"); } console.log(x); // 10 👉 Function is hoisted first, but variable assignment overrides it 4️⃣ Inside Scope var x = 1; function test() { console.log(x); // undefined var x = 2; } test(); 👉 Local x is hoisted → shadows global x 🔹 Where & When Do We Use Hoisting? ✔ Helps understand execution flow ✔ Useful in debugging unexpected undefined values ✔ Important when working with functions before declaration ✔ Critical in interviews & writing clean code 👉 Best Practice: Always declare variables at the top Prefer let and const to avoid confusion Avoid relying on hoisting in production code 🔹 Interview Points 💡 ✔ What is hoisting? ✔ Difference between var, let, and const hoisting ✔ What is Temporal Dead Zone? ✔ Function declaration vs expression hoisting ✔ Why does undefined occur instead of error? ✔ Hoisting inside function scope ✔ Real-time debugging scenarios 🔹 Quick Tip 👉 Hoisting ≠ moving code physically 👉 It’s just how JavaScript executes code internally 💬 Mastering hoisting = Strong foundation in JavaScript 📌 Save this for interviews & teaching sessions! #JavaScript #Frontend #WebDevelopment #CodingInterview #LearnToCode
To view or add a comment, sign in
-
-
JavaScript Interview Preparation — Most Asked Concepts When preparing for frontend interviews, strong JavaScript fundamentals are essential. Frameworks evolve rapidly, but the core concepts of JavaScript remain constant. Here are some common areas that interviewers focus on: 1. JavaScript Basics - Primitive vs Non-Primitive data types - typeof operator - null vs undefined - NaN behavior - Dynamic typing in JavaScript These questions assess your understanding of how JavaScript operates internally. 2. ES6 Features - Arrow functions - Template literals - Destructuring - Enhanced object literals - Promises ES6 introduced powerful and cleaner features that are prevalent in modern codebases. 3. Variables & Hoisting A frequently discussed topic. Understand: - var vs let vs const - Block scope vs function scope - Hoisting behavior - Temporal Dead Zone Many developers use these concepts daily but find it challenging to explain them during interviews. 4. Functions & Execution Context Key concepts include: - Arrow functions vs traditional functions - this keyword behavior - call(), apply(), bind() A grasp of execution context demonstrates a deep understanding of JavaScript runtime behavior. 5. Functional Programming Modern JavaScript relies on: - Higher-order functions - map() - filter() - reduce() These are commonly used in frontend codebases. 6. Scope & Closures One of the most crucial JavaScript topics. Understand: - Global scope - Local scope - Scope chain - Closures Closures frequently appear in frontend interview questions. 7. Browser Concepts Frontend developers should be familiar with: - DOM (Document Object Model) - BOM (Browser Object Model) - Event handling These concepts explain how JavaScript interacts with the browser. One truth about JavaScript interviews is that while frameworks change every few years, JavaScript fundamentals remain unchanged. A strong foundation makes learning frameworks like React, Angular, or Vue much easier. Save this for your next frontend interview
To view or add a comment, sign in
-
🚀 Promise.all() vs Promise.allSettled() — A Must-Know JavaScript Interview Concept If you’re preparing for frontend interviews, this question shows up a lot: 👉 What’s the difference between Promise.all() and Promise.allSettled()? Let’s break it down in a simple, interview-ready way 👇 🔹 Promise.all() — “All or Nothing” Promise.all() runs multiple promises in parallel but: • It resolves only if ALL promises succeed • If even one fails → it fails immediately (fail-fast) 📌 Example: const p1 = Promise.resolve("API 1 success"); const p2 = Promise.resolve("API 2 success"); const p3 = Promise.reject("API 3 failed"); Promise.all([p1, p2, p3]) .then(res => console.log(res)) .catch(err => console.log("Error:", err)); ✅ Output: Error: API 3 failed ✔️ Use when: • You need all results to proceed • Example: Page rendering depends on multiple APIs 🔹 Promise.allSettled() — “Get Everything” Promise.allSettled() waits for all promises to finish, no matter success or failure. • Returns status for each promise • Never fails as a whole 📌 Example: Promise.allSettled([p1, p2, p3]) .then(res => console.log(res)); ✅ Output: [ { status: "fulfilled", value: "API 1 success" }, { status: "fulfilled", value: "API 2 success" }, { status: "rejected", reason: "API 3 failed" } ] ✔️ Use when: • APIs are independent • Example: Dashboard widgets, analytics panels 🎯 Interview-Ready Answer 👉 Promise.all() → fails immediately if any promise fails 👉 Promise.allSettled() → waits for all and returns individual results 💡 Follow-up Question 👉 “How do you get only successful results if some APIs fail?” const results = await Promise.allSettled(promises); const successResponses = results .filter(item => item.status === "fulfilled") .map(item => item.value); ⚡ Key Takeaway Understanding async behavior is not optional anymore. ✔ Helps debug real-world issues ✔ Improves API handling strategies ✔ Makes your interview answers stand out Small concepts like this create a big difference in senior-level interviews. #JavaScript #AsyncProgramming #FrontendDevelopment #WebDevelopment #ReactJS #InterviewPreparation #Promises #CodingInterview 👉 Follow Rahul R Jain for more real interview insights, React fundamentals, and practical frontend engineering content.
To view or add a comment, sign in
More from this author
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
Useful