🤔 JavaScript Developers – What will be the output of this code? const p1 = new Promise((resolve, reject) => { setTimeout(() => resolve("p1 is success"), 1000); }); const p2 = new Promise((resolve, reject) => { setTimeout(() => reject("p2 is failed"), 5000); }); const p3 = new Promise((resolve, reject) => { setTimeout(() => resolve("p3 is success"), 4000); }); Promise.allSettled([p1, p2, p3]).then((res) => { console.log(res); }); 💬 Question: What do you think will be printed in the console? A️) [ { status: "fulfilled", value: "p1 is success" }, { status: "fulfilled", value: "p3 is success" } ] B️) [ { status: "fulfilled", value: "p1 is success" }, { status: "rejected", reason: "p2 is failed" }, { status: "fulfilled", value: "p3 is success" } ] C️) "p2 is failed" D️ Something else? 👇 Drop your answer in the comments. #JavaScript #Promises #FrontendDevelopment #ReactJS #WebDevelopment #Promise.allSettled
JavaScript Promise.allSettled Output Explanation
More Relevant Posts
-
🚫 null vs undefined in JavaScript — Still Confused? Let’s Fix It 👇 As a frontend developer, I used to think null and undefined were the same… until they broke my logic in production 😅 Let’s simplify it: 👉 undefined Means a variable has been declared but not assigned a value yet let name; console.log(name); // undefined 👉 null Means you intentionally assigned “no value” let user = null; ⚡ Key Differences: 🔹 undefined = default state (JS assigns it) 🔹 null = intentional absence (you assign it) 🤯 Fun Fact: null == undefined // true null === undefined // false Why? Because == checks value only, while === checks value + type 🚨 Real-world Tip: Always use === instead of == to avoid unexpected bugs. 💡 When to use what? ✔️ Use undefined → when something is not initialized ✔️ Use null → when you want to explicitly clear a value Understanding this small difference can save you from BIG debugging headaches 🧠💥 #JavaScript #FrontendDevelopment #WebDevelopment #CodingTips #ReactJS #Developers
To view or add a comment, sign in
-
Crack Interviews with Strong JavaScript Fundamentals Master the essential JavaScript fundamentals every developer needs to write efficient, clean, and scalable code. This guide explains core concepts such as scope, closures, hoisting, promises, async/await, and the event loop in a simple and practical way. It’s perfect for beginners, frontend developers, and anyone preparing for technical interviews or looking to strengthen their JavaScript foundation. Closures (Explanation): A closure is when a function “remembers” variables from its outer scope, even after that outer function has finished executing. Enables data privacy and function factories. Example Code: function createCounter() { let count = 0; return function() { count++; return count; }; } const counter = createCounter(); console.log(counter()); // => 1 console.log(counter()); // => 2 #frontend #mern #javascript #react
To view or add a comment, sign in
-
Clean, organized code is the hallmark of a senior developer. If you're working in React or Next.js, you've likely seen import blocks that look like a cluttered junk drawer. Here is how you fix it using the Barrel Pattern. 📂 The Problem: Import Spaghetti When your project grows, you often end up with components nested deep in folders. Your imports start looking like this: import { Button } from '../../components/ui/Button'; import { Input } from '../../components/ui/Input'; import { Card } from '../../components/ui/Card'; It’s repetitive, hard to maintain, and frankly, a bit of an eyesore. 🎯 The Solution: Barrel Files A Barrel is a way to rollout multiple exports from a single file. By adding an index.ts (or .js) file to your folder, you can "re-export" everything. Step 1: Create components/ui/index.ts export * from './Button'; export * from './Input'; export * from './Card'; Step 2: Enjoy Clean Imports import { Button, Input, Card } from '@/components/ui'; 🚀 Why This Matters for Your Workflow * Readability: Your component files stay focused on logic, not a wall of 20 import lines. * Encapsulation: You decide what is public and what stays private within the folder. * Scalability: Moving files becomes much easier when you only have one central export point to update. > A Note on Tree Shaking: Modern bundlers (like Webpack 5 or Vite) handle barrel files well, but be careful in massive libraries. Always ensure your environment supports tree shaking to avoid pulling in unused code! #ReactJS #WebDevelopment #CleanCode #JavaScript #Frontend #ProgrammingTips #NextJS #SoftwareEngineering
To view or add a comment, sign in
-
-
Memory Management — CJS vs ESM Most JavaScript developers use require or import every day without thinking about what actually happens in memory. The difference between CommonJS and ES Modules is not just syntax. It is a fundamentally different approach to how modules share data. -> CommonJS — require() When you require a module in CommonJS, Node.js executes the module and returns a copy of its exports object. That copy is then cached. If the original module's values change after the initial load, the module that required it does not see those changes. It gets a snapshot. Not a live reference. This is the caching issue shown in the diagram. Multiple parts of your application can require the same module and each gets its own copy of the exported value at the time of import. If that value mutates, the copies diverge from the source. -> ES Modules — import ES Modules work fundamentally differently. Instead of copying values, they create live bindings to the original module's exports. If the source module's exported value changes, every module that imported it sees the updated value immediately. This is what live bindings means. The connection stays alive. The reference does not go stale. Why this matters in practice: -> Singleton patterns behave correctly with ESM because there is only one live reference, not multiple copies -> Circular dependencies are handled more predictably in ESM -> Tree shaking works with ESM because bundlers can statically analyze what is actually used -> CommonJS is dynamic — require can be called anywhere, conditionally, inside functions. ESM imports are static and must be at the top level The JavaScript ecosystem is actively migrating toward ESM. Node.js fully supports it. Most modern bundlers default to it. Understanding the memory model difference explains why certain bugs appear in CJS codebases and disappear when moving to ESM. Are you still using CommonJS in your Node.js projects or have you migrated to ES Modules? #JavaScript #NodeJS #ESModules #WebDevelopment #Developers #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
Closures in React: powerful concept, subtle bugs Closures are a fundamental concept in JavaScript. They also explain some of the most confusing bugs that appear in React applications. A closure happens when a function captures variables from the scope where it was created. Those variables remain accessible even after the outer function has finished executing. In React, every render creates a new scope. When a function is defined inside a component, it closes over the values from that specific render. This becomes important when using hooks like useMemo and useCallback. If the dependency array is incomplete, the function may keep referencing outdated values from a previous render. Common situations where this appears: • useCallback capturing an old state value • useMemo computing something with stale props • event handlers referencing outdated variables The result is what developers often call a stale closure. The UI updates, but the function is still working with old data. This is why dependency arrays matter. They are not only about performance. They ensure the function is recreated when its captured values change. A good rule of thumb is simple. If a value is used inside useMemo or useCallback, it usually belongs in the dependency array. I added a small example in the comments showing how a stale closure happens in practice and how to fix it.
To view or add a comment, sign in
-
-
JavaScript Array Methods You Should Master as a Developer If you’re working with arrays daily (especially in React), these methods are not optional… they’re essential Let’s make them super simple 👇 -> filter() → returns a new array with elements that match a condition -> map() → transforms each element into something new -> find() → gives the first matching element -> findIndex() → returns index of the first match -> every() → checks if all elements satisfy a condition -> some() → checks if at least one element satisfies a condition -> includes() → checks if a value exists in the array -> concat() → merges arrays into a new array -> fill() → replaces elements with a fixed value (modifies array) -> push() → adds elements to the end (modifies array) -> pop() → removes last element (modifies array) ⚡ Pro Insight (Most Developers Miss This): -> Methods like map, filter, concat → return new arrays (safe ✅) -> Methods like push, pop, fill → modify original array (be careful ⚠️) 💡 Key Takeaway: If you're building UI… -> map() = rendering lists -> filter() = conditional rendering -> find() = quick lookups Master these, and your code becomes cleaner, shorter, and more powerful Save this for quick revision 📌 #JavaScript #FrontendDevelopment #ReactJS #WebDevelopment #CodingTips #CleanCode #Developers #LearnInPublic #DeveloperJourney
To view or add a comment, sign in
-
-
# 5. JavaScript JavaScript is the backbone of modern web development. From simple websites to complex applications, it powers everything you see on the internet. One of JavaScript’s greatest strengths is its versatility. It runs on browsers, servers (Node.js), and even mobile and desktop applications. This makes it a must-have skill for developers. JavaScript enables dynamic and interactive user experiences. Features like event handling, asynchronous programming, and APIs allow developers to create responsive and real-time applications. With the rise of frameworks like React, Angular, and Vue, JavaScript has become even more powerful. These tools simplify development and enable scalable architecture. Another key advantage is its vast ecosystem. With millions of libraries and packages available via npm, developers can build applications faster than ever. In today’s tech landscape, mastering JavaScript is not optional — it’s essential. Whether you’re a frontend, backend, or full-stack developer, JavaScript plays a critical role. #JavaScript #WebDevelopment #Coding #Programming #Frontend #Backend #FullStack
To view or add a comment, sign in
-
🚀 Debugging JWT Auth — A Small Mistake That Cost Me Hours Today I ran into a classic authentication issue while working with NestJS + Next.js — and it’s a good reminder of how small misunderstandings can break the whole flow. 🔍 The Problem After login, I noticed that my localStorage was saving: token: "string" Instead of an actual JWT like: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ⚠️ Clearly something was off. 🧠 The Root Cause My backend response looked like this: { "success": true, "data": { ...userDetails }, "token": "REAL_JWT_TOKEN" } But in my frontend, I made this mistake: const userData = res.data.data; localStorage.setItem("token", userData.token); // ❌ wrong 👉 The token wasn’t inside data — it was at the root level. ✅ The Fix const userData = res.data.data; const token = res.data.token; localStorage.setItem("token", token); localStorage.setItem("userData", JSON.stringify(userData)); 🔥 Debug smarter, not harder. #WebDevelopment #NestJS #NextJS #JWT #Authentication #Debugging #FullStack #JavaScript
To view or add a comment, sign in
-
💡 JavaScript Essentials: Closures & Hoisting Explained Simply If you're working with JavaScript, especially in frameworks like Angular or React, understanding closures and hoisting is a must. Here’s a quick breakdown 👇 🔹 Closures A closure is created when a function remembers its outer scope even after that outer function has finished execution. 👉 Why it matters? Helps in data encapsulation Used in callbacks, event handlers, and async code Powers concepts like private variables Example: function outer() { let count = 0; return function inner() { count++; console.log(count); } } const counter = outer(); counter(); // 1 counter(); // 2 🔹 Hoisting Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. 👉 Key points: var is hoisted and initialized with undefined let and const are hoisted but stay in the Temporal Dead Zone Function declarations are fully hoisted Example: console.log(a); // undefined var a = 10; console.log(b); // ReferenceError let b = 20; 🚀 Takeaway Closures help you retain state, while hoisting explains how JavaScript reads your code before execution. Mastering these will level up your debugging skills and help you write cleaner, predictable code. #JavaScript #WebDevelopment #Frontend #Angular #React #Coding #Developers
To view or add a comment, sign in
-
Most React Native codebases become a mess by month 3. Not because the developer was bad. Because nobody agreed on a structure from day one. Here's the folder structure I use on every project 👇 src/ ├── components/ → reusable UI only ├── screens/ → one file per screen ├── navigation/ → all route config here ├── hooks/ → useAuth, usePlayer, useBooking ├── store/ → Redux slices ├── services/ → ALL API calls live here ├── utils/ → helpers & constants ├── types/ → TypeScript interfaces └── assets/ → images & fonts 3 rules I never break: 🔴 API calls never go inside components 🟡 Every colour lives in theme.ts — nowhere else 🟢 Types folder grows with the project — never skip it Junior me put everything in /components. 6 months later it had 60 files and zero logic separation. Never again. Save this before your next project 👇 #ReactNative #TypeScript #CleanCode #MobileDev #JavaScript #2026
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