● Interview Question: What are Promises in JavaScript? - A Promise is an object that represents the eventual completion or failure of an asynchronous operation. - It helps handle async code without callback hell. ● Promise States A Promise can be in one of three states: - Pending – Initial state - Fulfilled – Operation completed successfully - Rejected – Operation failed ● Creating Promise const promise = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Task completed"); } else { reject("Task failed"); } }); ● Consuming Promise promise .then(result => console.log(result)) .catch(error => console.log(error)) .finally(() => console.log("Done")); where :- .then() -> handles success .catch() -> handles errors .finally() -> always executes Promises make async code readable and manageable #JavaScript #Promises #AsyncJavaScript #InterviewPrep #WebDevelopment #Frontend #MERN #LearnInPublic #CodingJourney #30DaysOfJavaScript #Backend #BDRM #BackendDevWithRahulMaheshwari
JavaScript Promises: Async Code Handling with Resolve and Reject
More Relevant Posts
-
Day 1/50 – JavaScript Interview Question? Question: What is the Temporal Dead Zone (TDZ) in JavaScript? Simple Answer: The Temporal Dead Zone is the period between entering a scope and the actual declaration of a let or const variable, during which the variable cannot be accessed. 🧠 Why it matters in real projects: Understanding TDZ helps you avoid ReferenceError bugs in your applications. Unlike var which returns undefined when accessed before declaration, let and const throw errors, making your code more predictable and easier to debug. 💡 One common mistake: Assuming that because let and const are "hoisted" like var, they can be accessed before their declaration. They are hoisted, but remain uninitialized in the TDZ. 📌 Bonus: console.log(myVar); // undefined console.log(myLet); // ReferenceError: Cannot access before initialization var myVar = 1; let myLet = 2; #JavaScript #WebDevelopment #Frontend #LearnInPublic
To view or add a comment, sign in
-
Controlling `this` in JavaScript: Call vs. Apply vs. Bind. 🎮 One of the most common interview questions for mid-level developers is: "𝑊ℎ𝑎𝑡 𝑖𝑠 𝑡ℎ𝑒 𝑑𝑖𝑓𝑓𝑒𝑟𝑒𝑛𝑐𝑒 𝑏𝑒𝑡𝑤𝑒𝑒𝑛 𝐶𝑎𝑙𝑙, 𝐵𝑖𝑛𝑑, 𝑎𝑛𝑑 𝐴𝑝𝑝𝑙𝑦?" They all do the same core job: They allow you to manually set what `this` refers to inside a function. But they do it in slightly different ways. 𝐇𝐞𝐫𝐞 𝐢𝐬 𝐭𝐡𝐞 𝟏𝟎-𝐬𝐞𝐜𝐨𝐧𝐝 𝐛𝐫𝐞𝐚𝐤𝐝𝐨𝐰𝐧: 1️⃣ 𝐂𝐚𝐥𝐥 & 𝐀𝐩𝐩𝐥𝐲 (𝐓𝐡𝐞 𝐈𝐦𝐦𝐞𝐝𝐢𝐚𝐭𝐞 𝐈𝐧𝐯𝐨𝐤𝐞𝐫𝐬) Both of these execute the function 𝑖𝑚𝑚𝑒𝑑𝑖𝑎𝑡𝑒𝑙𝑦. The only difference is how they handle arguments. • 𝐂𝐚𝐥𝐥: Passes arguments individually (comma-separated). • 𝑀𝑛𝑒𝑚𝑜𝑛𝑖𝑐: 𝐂all = 𝐂ommas. • 𝐀𝐩𝐩𝐥𝐲: Passes arguments as a single Array. • 𝑀𝑛𝑒𝑚𝑜𝑛𝑖𝑐: 𝐀pply = 𝐀rray. 2️⃣ 𝐁𝐢𝐧𝐝 (𝐓𝐡𝐞 𝐏𝐥𝐚𝐧𝐧𝐞𝐫) • 𝐁𝐢𝐧𝐝: Does NOT execute the function immediately. • Instead, it returns a 𝐧𝐞𝐰 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐜𝐨𝐩𝐲 with the `this` context permanently locked (bound) to the object you specified. You can then call this new function whenever you want later. 𝐖𝐡𝐲 𝐢𝐬 𝐭𝐡𝐢𝐬 𝐮𝐬𝐞𝐟𝐮𝐥? It allows "Method Borrowing." You can use a method from one object (like a helper function) and use it on a completely different object, just by changing the `this` context! Check out the syntax comparison below! 👇 Which one do you use most often? I find `bind` essential for passing methods into React components or event listeners! #JavaScript #WebDevelopment #CodingInterviews #SoftwareEngineering #Frontend #JSConcepts
To view or add a comment, sign in
-
-
🔄 𝗣𝗿𝗼𝗺𝗶𝘀𝗲𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 – 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱 𝗦𝗶𝗺𝗽𝗹𝘆 𝘄𝗶𝘁𝗵 𝗥𝗲𝗮𝗹 𝗘𝘅𝗮𝗺𝗽𝗹𝗲𝘀 Promises in JavaScript are the backbone of modern asynchronous code. If you understand Promises well, callbacks, async/await, and API handling become much easier. This guide explains Promises in a simple, practical, and interview-ready way. 🧠 What You’ll Learn ✅ What a Promise is & why it exists ✅ Promise states: pending, fulfilled, rejected ✅ .then(), .catch(), .finally() ✅ Promise chaining & error handling ✅ Promise.all, Promise.race, Promise.any, Promise.allSettled ✅ How Promises power async / await ✅ Common mistakes & interview traps 🎯 Why this matters Most JavaScript bugs come from misunderstanding async behavior. Mastering Promises helps you write cleaner, predictable, and scalable code. 👨💻 Best for • JavaScript beginners → intermediate • Frontend & Full Stack developers • Interview preparation • Anyone working with APIs 𝗜 𝗵𝗮𝘃𝗲 𝗽𝗿𝗲𝗽𝗮𝗿𝗲𝗱 𝗖𝗼𝗺𝗽𝗹𝗲𝘁𝗲 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗣𝗿𝗲𝗽𝗮𝗿𝗮𝘁𝗶𝗼𝗻 𝗚𝘂𝗶𝗱𝗲 𝗳𝗼𝗿 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿. 𝗚𝗲𝘁 𝘁𝗵𝗲 𝗚𝘂𝗶𝗱𝗲 𝗵𝗲𝗿𝗲 👉 https://lnkd.in/dygKYGVx 𝗜’𝘃𝗲 𝗯𝘂𝗶𝗹𝘁 𝟴+ 𝗿𝗲𝗰𝗿𝘂𝗶𝘁𝗲𝗿-𝗿𝗲𝗮𝗱𝘆 𝗽𝗼𝗿𝘁𝗳𝗼𝗹𝗶𝗼 𝘄𝗲𝗯𝘀𝗶𝘁𝗲𝘀 𝗳𝗼𝗿 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀. 𝗚𝗲𝘁 𝘁𝗵𝗲 𝗽𝗼𝗿𝘁𝗳𝗼𝗹𝗶𝗼𝘀 𝗵𝗲𝗿𝗲 👉 https://lnkd.in/drqV5Fy3 #JavaScript #Promises #AsyncJavaScript #WebDevelopment #FrontendDeveloper #Programming #InterviewPreparation
To view or add a comment, sign in
-
⏱️ JavaScript Timers – Understanding setTimeout Like a Pro setTimeout is one of the most commonly used async features in JavaScript – but many developers misunderstand how it really works. It does NOT execute exactly after the given time. It executes after the minimum delay + when the call stack is free. 🧠 Important Facts About setTimeout It is handled by the browser / Node timer API Callback goes to the Macrotask Queue Execution depends on the Event Loop 0 ms delay does NOT mean instant execution 🚀 Key Takeaways setTimeout is asynchronous Delay is the minimum wait time, not guaranteed time Even setTimeout(fn, 0) waits for: current code to finish event loop to pick it up 💡 Interview Insight If someone asks: “Why doesn’t setTimeout 0 run immediately?” Answer: 👉 Because JavaScript must finish synchronous code first, and timers run later through the event loop. If this clarified your understanding of timers, drop a 👍 #JavaScript #setTimeout #WebDevelopment #Frontend #Coding #InterviewPrep
To view or add a comment, sign in
-
-
📘 DSA Practice | Single Number (JavaScript) Today I solved a classic DSA problem: Finding the Single Number in an array using JavaScript. 🔹 Problem Statement Given a non-empty array of integers, every element appears twice except for one. Find that single one. 📌 Example Input: [2, 2, 1] Output: 1 ✅ My Approach (Using Object / Hash Map) I used an object to count the frequency of each number. 💡 Idea Traverse the array and store counts in an object Loop through the object Return the number whose count is 1 🧠 Code var singleNumber = function(nums) { let obj = {} for (let i = 0; i < nums.length; i++) { let currentValue = nums[i] obj[currentValue] = obj[currentValue] ? obj[currentValue] + 1 : 1 } for (let item in obj) { if (obj[item] === 1) { return Number(item) } } }; console.log(singleNumber([2, 2, 1])); // 1 ⏱ Time & Space Complexity • Time: O(n) • Space: O(n) (extra object used) ✔ Easy to understand ✔ Beginner-friendly ✔ Works well for learning hash-based logic ⚡ Optimized Version (Using XOR – Interview Preferred) We can solve this problem without extra memory using the XOR operator. 💡 Why XOR? • a ^ a = 0 • a ^ 0 = a • Order doesn’t matter So all duplicate numbers cancel out, leaving the single number. 🚀 Optimized Code var singleNumber = function(nums) { let result = 0; for (let num of nums) { result ^= num; } return result; }; console.log(singleNumber([2, 2, 1])); // 1 ⏱ Time & Space Complexity • Time: O(n) • Space: O(1) ✅ 🔥 Best choice for interviews & production-level efficiency 🧠 Key Takeaways ✔ Hash maps are great for clarity ✔ XOR gives optimal performance ✔ Always think about space optimization ✔ Simple logic can beat complex code #JavaScript #DSA #ProblemSolving #BackendDeveloper #CodingInterview #LearningInPublic #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🤔JavaScript behaves differently with values depending on what you’re working with and this trips up a lot of interview answers. 🧠 JavaScript interview question What is the difference between primitive and reference types? ✅ Short answer • Primitives are copied by value • Objects are copied by reference • Equality checks references, not structure 🔍 A bit more detail • Primitive types number, string, boolean, null, undefined, symbol, bigint Stored as values Assigning or passing them creates a copy • Reference types objects, arrays, functions Variables store a reference to the same object Mutating through one reference affects all others • Equality {} === {} is false Same shape does not mean same reference 💻 Example // primitive copy let a = 5 let b = a b = 7 console.log(a) // 5 // reference copy const p = { n: 1 } const q = p q.n = 2 console.log(p.n) // 2 ⚠️ Small but important detail JavaScript always passes arguments by value. For objects, that value is the reference. Reassigning a parameter does nothing. Mutating the object does. I’m sharing one JavaScript interview-style question per day to build calm, solid fundamentals step by step. #javascript #frontend #interviewprep #webdevelopment
To view or add a comment, sign in
-
🚀 Js Interview Trap Most Developers Fall Into ❌ “JavaScript is single-threaded, so it runs one thing at a time.” Sounds correct… but it’s incomplete. Let’s fix that 👇 🧠 How JavaScript ACTUALLY works: JavaScript runs on a single thread, but it can still handle async tasks efficiently using: ✅ Call Stack ✅ Web APIs (setTimeout, fetch, DOM events) ✅ Callback Queue / Microtask Queue ✅ Event Loop ⚡ Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 📝 Output: Start End Promise Timeout ❓ Why? Promise.then → Microtask Queue (higher priority) setTimeout → Callback Queue Event Loop executes microtasks first 🎯 Interview takeaway: JavaScript is single-threaded, but non-blocking because of the event loop + async architecture. If this explanation helped you, 👍 #JavaScript #Frontend #WebDevelopment #ReactJS #InterviewPrep #100DaysOfCode
To view or add a comment, sign in
-
🤔 Closures exist because JavaScript remembers where a function was created, not just where it’s called. That single rule explains a lot of “magic” behavior in JS. 🧠 JavaScript interview question What is a closure? ✅ Short answer • A closure is a function plus its lexical environment (function and it's "backpack" or COVE -> Closed Over Variable Environment) • It remembers variables from its outer scope • Those variables stay alive even after the outer function finishes 🔍 A bit more detail • JavaScript uses lexical scope • Inner functions can access variables from where they were defined • Closures keep references to variables, not copies • That’s why values can change over time 💻 Example function makeCounter() { let count = 0; return function () { count++; return count; }; } const counter = makeCounter(); counter(); // 1 counter(); // 2 counter(); // 3 ⚠️ Small but important detail Closures don’t freeze values. They hold live links to variables. That’s why let works correctly in loops with async code, and var often surprises people. 👋 I’m sharing one JavaScript interview-style concept every day to build intuition, not just memorize rules. #javascript #frontend #webdevelopment #interviewprep #learning
To view or add a comment, sign in
-
💡 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗖𝗼𝗱𝗶𝗻𝗴 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 (𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁) 𝗤: 𝗛𝗼𝘄 𝘄𝗼𝘂𝗹𝗱 𝘆𝗼𝘂 𝗶𝗺𝗽𝗹𝗲𝗺𝗲𝗻𝘁 𝗮 𝘂𝘁𝗶𝗹𝗶𝘁𝘆 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝘁𝗵𝗮𝘁 𝗺𝗲𝗮𝘀𝘂𝗿𝗲𝘀 𝘁𝗵𝗲 𝗲𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝘁𝗶𝗺𝗲 𝗼𝗳 𝗮 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻, 𝘀𝘂𝗽𝗽𝗼𝗿𝘁𝗶𝗻𝗴 𝗯𝗼𝘁𝗵 𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗮𝗻𝗱 𝗮𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀? 𝗥𝗲𝗾𝘂𝗶𝗿𝗲𝗺𝗲𝗻𝘁𝘀: • Accept a function fn and its arguments • Log execution time in milliseconds • Return the result of fn • Work for both sync & async functions ✅ 𝗔𝗻𝘀𝘄𝗲𝗿: below ⚠️ 𝗪𝗵𝗲𝗿𝗲 𝗺𝗼𝘀𝘁 𝗰𝗮𝗻𝗱𝗶𝗱𝗮𝘁𝗲𝘀 𝗳𝗮𝗶𝗹: ❌ Not using finally → execution time not logged on errors ❌ Thinking return exits immediately and skips other code ❌ Writing separate logic for sync vs async functions 🧠 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗜𝗻𝘀𝗶𝗴𝗵𝘁: 𝗮𝘄𝗮𝗶𝘁 𝘄𝗼𝗿𝗸𝘀 𝗳𝗼𝗿 𝗯𝗼𝘁𝗵 𝘀𝘆𝗻𝗰 𝗮𝗻𝗱 𝗮𝘀𝘆𝗻𝗰 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗳𝗶𝗻𝗮𝗹𝗹𝘆 𝗮𝗹𝘄𝗮𝘆𝘀 𝗲𝘅𝗲𝗰𝘂𝘁𝗲𝘀, 𝗲𝘃𝗲𝗻 𝘄𝗵𝗲𝗻 𝗿𝗲𝘁𝘂𝗿𝗻 𝗶𝘀 𝗶𝗻𝘀𝗶𝗱𝗲 𝘁𝗿𝘆 📌 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: measureExecutionTime(add, 2, 3); await measureExecutionTime(delay, 1000); 👉 𝗪𝗼𝘂𝗹𝗱 𝘆𝗼𝘂 𝘂𝘀𝗲 𝗗𝗮𝘁𝗲.𝗻𝗼𝘄() 𝗼𝗿 𝗽𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲.𝗻𝗼𝘄() 𝗳𝗼𝗿 𝘁𝗵𝗶𝘀 𝗶𝗻 𝗽𝗿𝗼𝗱𝘂𝗰𝘁𝗶𝗼𝗻? #JavaScript #AsyncAwait #CodingInterview #Frontend #WebDevelopment #DevTips #InterviewPrep #interview #JavaScript #Promises #Frontend #WebDevelopment #CodingTips #InterviewPrep #CSS #Frontend #WebDevelopment #ReactJS #JavaScript #UI #FrontendTips #100DaysOfCode #HTML #FrontendDeveloper #LearnInPublic #ES6 #ModernJavaScript
To view or add a comment, sign in
-
-
JavaScript Interview Question: Que: What is Async & Await? Ans: Async Function: The async function allows to make a synchronous function to asynchronous. This ensures that the execution thread is not blocked. - Preceding a function with async ensures it always returns a Promise. - If the function returns a value that is not a promise, JavaScript automatically wraps it in a resolved promise. Await Keyword: The await keyword is used to wait for a promise to resolve. - Used only inside async functions or modules, - await pauses the execution of the function until the promise is settled (either fulfilled or rejected). - While the specific function is paused, the rest of the application remains responsive because the main thread is not blocked. Why Use Async/Await? 1. Readability: It allows asynchronous code to look and behave like synchronous code, making it easier to follow than traditional .then() promise chains (often called "callback hell"). 2. Error Handling: You can use standard try...catch blocks to manage errors, just as you would with synchronous code. 3. Non-Blocking: It prevents the user interface from "freezing" during long-running tasks. #javascript #async #await #conceptsOfJavaScript #freeLancer #reactJs #frontend #softwareDeveloper #nodeJs #backend #fullStack #interviewQuestion
To view or add a comment, sign in
-
Explore related topics
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