Day 11/50 – JavaScript Interview Question? Question: What is the difference between Promise.all() and Promise.race()? Simple Answer: Promise.all() waits for all promises to resolve (or one to reject) and returns an array of results. Promise.race() returns as soon as the first promise settles (resolves or rejects), ignoring the others. 🧠 Why it matters in real projects: Use Promise.all() when you need multiple API calls to complete before proceeding (like fetching user data and their posts). Use Promise.race() for implementing timeouts or choosing the fastest response from multiple sources. 💡 One common mistake: Not realizing that Promise.all() fails fast—if any promise rejects, the entire operation fails immediately, even if other promises are still pending. 📌 Bonus: // Promise.all - all must succeed const results = await Promise.all([ fetch('/api/user'), fetch('/api/posts'), fetch('/api/comments') ]); // If any fails, all fail // Promise.race - first one wins const result = await Promise.race([ fetch('/api/data'), new Promise((_, reject) => setTimeout(() => reject('Timeout'), 5000) ) ]); // Implements a 5-second timeout // Use Promise.allSettled() to get all results regardless of failures #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
Promise.all() vs Promise.race() in JavaScript
More Relevant Posts
-
Day 17/50 – JavaScript Interview Question? Question: What is debouncing and how do you implement it? Simple Answer: Debouncing is a technique that delays function execution until a certain amount of time has passed since the last invocation. It's perfect for limiting how often a function runs in response to rapid events. 🧠 Why it matters in real projects: Debouncing is essential for optimizing search autocomplete, form validation, window resize handlers, and scroll events. Without it, you'd make hundreds of unnecessary API calls or trigger expensive calculations on every keystroke. 💡 One common mistake: Confusing debouncing with throttling. Debouncing waits for a pause in events, while throttling executes at regular intervals regardless of event frequency. 📌 Bonus: // Debounce implementation function debounce(func, delay) { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; } // Usage: Search autocomplete const searchAPI = (query) => { console.log('Searching for:', query); // Actual API call here }; const debouncedSearch = debounce(searchAPI, 500); // User types "javascript" // Only makes 1 API call after user stops typing for 500ms searchInput.addEventListener('input', (e) => { debouncedSearch(e.target.value); }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
🛑 JavaScript Interview: Do you know the Return Types? We use .map(), .filter(), and .reduce() every day. But can you explain precisely what they Return? Here is the breakdown that separates Junior Devs from Senior Devs: 1️⃣ .map() ➡️ Returns a New Array 📦 It creates a modified copy of the original array. Input: [1, 2, 3] (Array) Output: [2, 4, 6] (Array of same length) Use case: Transformation. 2️⃣ .filter() ➡️ Returns a New Array 📦 It returns a subset of the original array. Input: [1, 2, 3] (Array) Output: [2] (Array of smaller length) Use case: Selection/Removal. 3️⃣ .reduce() ➡️ Returns a Single Value 💎 This is the game changer. It processes the array to produce ONE result. Input: [1, 2, 3] (Array) Output: 6 (Number / String / Object) Use case: Accumulation (Sum, Object creation). 💡 The "Gotcha": If you assign .forEach() to a variable, it returns undefined. But .map() and .filter() will always give you an Array. Which one do you find most powerful? For me, .reduce() is pure magic. ✨ #javascript #webdevelopment #codingtips #reactjs #frontenddeveloper #softwareengineering #interviewquestions
To view or add a comment, sign in
-
Day 13/50 – JavaScript Interview Question? Question: What is hoisting in JavaScript? Simple Answer: Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the compilation phase. Function declarations are fully hoisted, var declarations are hoisted but initialized as undefined, and let/const are hoisted but remain in the Temporal Dead Zone. 🧠 Why it matters in real projects: Understanding hoisting helps you avoid confusing bugs and write more predictable code. It explains why you can call functions before they're declared and why accessing var variables before declaration returns undefined instead of an error. 💡 One common mistake: Thinking hoisting physically moves code. It doesn't—it's about when variables and functions are registered in memory during the creation phase. 📌 Bonus: // Function hoisting - works! greet(); // "Hello" function greet() { console.log("Hello"); } // var hoisting - returns undefined console.log(name); // undefined (not ReferenceError) var name = "Alice"; // let/const - Temporal Dead Zone console.log(age); // ReferenceError let age = 25; // Function expressions are NOT fully hoisted sayHi(); // TypeError: sayHi is not a function var sayHi = function() { console.log("Hi"); }; #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 26/50 – JavaScript Interview Question? Question: What is currying in JavaScript? Simple Answer: Currying transforms a function that takes multiple arguments into a sequence of functions, each taking a single argument. Instead of add(a, b), you get add(a)(b). 🧠 Why it matters in real projects: Currying enables partial application, function composition, and more reusable code. It's fundamental to functional programming libraries like Ramda and is used in Redux middleware, event handlers, and configuration functions. 💡 One common mistake: Over-currying simple functions where it adds complexity without benefit. Use currying when you need partial application or composition, not everywhere. 📌 Bonus: // Regular function function add(a, b, c) { return a + b + c; } add(1, 2, 3); // 6 // Curried version function curriedAdd(a) { return function(b) { return function(c) { return a + b + c; }; }; } curriedAdd(1)(2)(3); // 6 // Practical use: Partial application const add5 = curriedAdd(5); const add5and10 = add5(10); console.log(add5and10(3)); // 18 // Generic curry function function curry(fn) { return function curried(...args) { if (args.length >= fn.length) { return fn.apply(this, args); } return function(...nextArgs) { return curried.apply(this, [...args, ...nextArgs]); }; }; } // Usage const multiply = (a, b, c) => a * b * c; const curriedMultiply = curry(multiply); curriedMultiply(2)(3)(4); // 24 curriedMultiply(2, 3)(4); // 24 - flexible! #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #FunctionalProgramming #Currying #WebDev #InterviewPrep
To view or add a comment, sign in
-
Day 17 – JavaScript Interview Q&A Series 🚀 Continuing my JavaScript interview learnings – Day Series, focusing on how data is handled in real-world frontend applications. 🔹 Day 17 Topic: Mutability vs Immutability 1️⃣ What is Mutability? Mutability means changing the original object or array directly. 📌 Examples: • push(), pop() • Direct object property assignment 2️⃣ What is Immutability? Immutability means creating a new copy instead of modifying existing data. 📌 Examples: • Spread operator (...) • map, filter, concat 3️⃣ Why is immutability important? • Predictable state updates • Efficient change detection • Easier debugging and time-travel debugging 4️⃣ How does this affect React & Angular? • React relies on reference changes to trigger re-renders • Angular’s OnPush change detection benefits from immutability 5️⃣ Interview takeaway Immutability helps avoid side effects and unexpected UI bugs. 📌 This concept separates beginner vs experienced frontend developers. ➡️ Day 18 coming soon… (JavaScript Design Patterns – Module, Singleton) 🧠⚙️ #JavaScript #Immutability #FrontendDeveloper #InterviewPreparation #Angular #React #LearningInPublic
To view or add a comment, sign in
-
Day 12/50 – JavaScript Interview Question? Question: What is the difference between deep copy and shallow copy? Simple Answer: A shallow copy duplicates only the top-level properties, keeping references to nested objects. A deep copy recursively duplicates all levels, creating completely independent copies. 🧠 Why it matters in real projects: Understanding this prevents bugs when modifying copied objects. In React/Redux, shallow copies are often sufficient for state updates, but nested state requires deep copying. Financial data, user profiles, and configuration objects often need deep copies. 💡 One common mistake: Using spread operator {...obj} or Object.assign() and thinking you have a deep copy. These only perform shallow copies! 📌 Bonus: const original = { name: 'John', address: { city: 'NYC' } }; // Shallow copy - nested objects still shared const shallow = { ...original }; shallow.address.city = 'LA'; console.log(original.address.city); // "LA" - Oops! // Deep copy options: // 1. Modern way (careful with functions/dates) const deep1 = structuredClone(original); // 2. JSON method (loses functions, dates become strings) const deep2 = JSON.parse(JSON.stringify(original)); // 3. Use lodash for complex objects const deep3 = _.cloneDeep(original); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 20/50 – JavaScript Interview Question? Question: What is prototypal inheritance in JavaScript? Simple Answer: Prototypal inheritance is JavaScript's mechanism for objects to inherit properties and methods from other objects through the prototype chain. When you access a property, JavaScript first checks the object itself, then walks up the prototype chain until it finds the property or reaches null. 🧠 Why it matters in real projects: Understanding prototypes is fundamental to JavaScript's object model. It's how classes work under the hood, how built-in methods like Array.prototype.map() are available, and how you can extend native objects or create efficient object hierarchies. 💡 One common mistake: Confusing __proto__ (the actual link) with prototype (the property on constructor functions). Also, modifying built-in prototypes like Array.prototype in production code is considered a bad practice. 📌 Bonus: // Constructor function function Person(name) { this.name = name; } // Add method to prototype (shared by all instances) Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; }; const alice = new Person('Alice'); alice.greet(); // "Hello, I'm Alice" // Prototype chain alice.hasOwnProperty('name'); // true (own property) alice.hasOwnProperty('greet'); // false (inherited) alice.__proto__ === Person.prototype; // true // Modern ES6 class syntax (same prototype underneath) class Employee extends Person { constructor(name, title) { super(name); this.title = title; } } const bob = new Employee('Bob', 'Developer'); console.log(bob.greet()); // Inherits from Person #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Prototypes #OOP
To view or add a comment, sign in
-
JavaScript interview question that fails 80% of candidates: Implement Promise.all from scratch. Most answers: "Loop through promises and resolve when all done" That gets you 3/10. Here's the 9/10 answer: function promiseAll(promises) { return new Promise((resolve, reject) => { const results = []; let completed = 0; promises.forEach((promise, index) => { Promise.resolve(promise) .then(value => { results[index] = value; completed++; if (completed === promises.length) { resolve(results); } }) .catch(reject); }); }); } Key points interviewers want: ✓ Handle non-promise values (Promise.resolve wrapper) ✓ Maintain order (results[index]) ✓ Reject on first failure ✓ Edge case: empty array There are 40+ JavaScript problems like this on FE Master. All with detailed solutions. Link in the first comment #javascript #frontend
To view or add a comment, sign in
-
Day 23/50 – JavaScript Interview Question? Question: What is memoization and how do you implement it? Simple Answer: Memoization is an optimization technique that caches function results based on input arguments. When the function is called again with the same arguments, it returns the cached result instead of recalculating. 🧠 Why it matters in real projects: Memoization dramatically improves performance for expensive computations like recursive Fibonacci, API response parsing, or complex filtering/sorting. React's useMemo and React.memo are built on this principle to prevent unnecessary re-renders. 💡 One common mistake: Over-memoizing everything, which adds memory overhead. Only memoize truly expensive operations. Also, not considering cache size limits, which can cause memory leaks in long-running applications. 📌 Bonus: // Basic memoization implementation function memoize(fn) { const cache = new Map(); return function(...args) { const key = JSON.stringify(args); if (cache.has(key)) { console.log('Returning cached result'); return cache.get(key); } const result = fn.apply(this, args); cache.set(key, result); return result; }; } // Usage: Expensive calculation const fibonacci = memoize((n) => { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); }); fibonacci(40); // Calculated once fibonacci(40); // Instant! (from cache) // React example const expensiveComponent = React.memo(({ data }) => { // Only re-renders if data changes }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 16/50 – JavaScript Interview Question? Question: What's the difference between == comparison and Object.is()? Simple Answer: Both compare values, but Object.is() is more precise. Unlike == (which coerces types) and === (which has special cases for NaN and -0), Object.is() treats NaN as equal to NaN and distinguishes between +0 and -0. 🧠 Why it matters in real projects: While you'll mostly use ===, Object.is() is important for precise comparisons in algorithms, polyfills, and when implementing state management libraries. React uses Object.is() internally for comparing dependencies in hooks. 💡 One common mistake: Not knowing that NaN === NaN is false in JavaScript, which can cause bugs when checking for NaN values in data processing. 📌 Bonus: // Special cases where === fails NaN === NaN // false Object.is(NaN, NaN) // true ✓ +0 === -0 // true Object.is(+0, -0) // false ✓ // For most cases, === works fine Object.is(5, 5) // true 5 === 5 // true Object.is('foo', 'foo') // true 'foo' === 'foo' // true // Checking for NaN the right way Number.isNaN(value) // ✓ Best practice Object.is(value, NaN) // ✓ Also works value !== value // ✓ Clever trick (only NaN !== itself) #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
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