💡JavaScript/React Tip💡 Using array reduce method helps to write better code. Let’s say you want to separate users based on their status or type. You might write code like this: const activeUsers = users.filter((user) => user.status === "active"); const inActiveUsers = users.filter((user) => user.status === "inactive"); Looks clean, right? But here's what's happening behind the scenes: 🔁 You're looping over the same array two times . Now imagine if your users list grows to 10,000+ users… That could affect performance. Also, If later you want to filter users by another status like disabled, then you need to add another line of code using filter function. ✅ Better approach: Use .reduce() to do all the grouping in one iteration. const { activeUsers, inActiveUsers } = users.reduce( (acc, user) => { if (user.status === "active") acc.activeUsers.push(user); if (user.status === "inactive") acc.inactiveUsers.push(user); return acc; }, { activeUsers: [], inactiveUsers: [] } ); 🧠 What’s happening here? → We loop through the array only once. → We check each user and push them into the appropriate bucket. → At the end, we destructure the object returned by the reduce method and get all two arrays. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #es6 #nextjs #webdevelopment
JavaScript Reduce Method for Efficient User Grouping
More Relevant Posts
-
Why #JavaScript Logic Confuses Even Developers 🧠💥 JavaScript is powerful... but it loves to surprise you. Here's why: Type Coercion Magic ✨ "11" + 1 // "111" "11" - 1 // 10 •means string concatenation •forces number conversion Same values, wildly different results! +"" // 0 +{} // NaN +[] // 0 Loose vs Strict Equality ⚖️ 0 == "0" // true 😱 0 === "0" // false ✅ Truthy & Falsy Surprises 🤯 Boolean("0") // true Boolean([]) // true Boolean({}) // true Boolean(0) // false JavaScript auto-converts types to be "helpful"... but that flexibility breeds bugs. How Pros Avoid This (React Dev Edition) 🚀 • Always use === over == • Convert explicitly: Number(), String(), Boolean() • Ditch implicit coercion • Switch to TypeScript for type safety in your React/Next.js apps JS isn't broken—it's just too flexible. Save this cheat sheet! 📌 Comment "JS" if you've been bitten by this. 👇 #JavaScript #WebDevelopment #ProgrammingHumor #CodingLife #Frontend #Developer #codingirlben #React #DeveloperLife #ReactJS #CodingMemes #DevHumor
To view or add a comment, sign in
-
-
🚀 Hoisting (JavaScript) Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope before code execution. Note that only the declarations are hoisted, not the initializations. This means you can use a variable or function before it's declared in the code, but if it's not initialized, it will be `undefined` for variables or the function definition will be available for functions. Understanding hoisting is important for avoiding unexpected behavior and writing cleaner code. Variables declared with `let` and `const` are also hoisted, but they are not initialized and accessing them before declaration results in a `ReferenceError`. Learn more on our website: https://techielearns.com #JavaScript #WebDev #Frontend #JS #professional #career #development
To view or add a comment, sign in
-
-
🚀 Object Methods (JavaScript) Object methods are functions that are stored as properties of an object. They allow you to associate behavior with an object. The `this` keyword inside a method refers to the object that the method is called on. This allows methods to access and manipulate the object's properties. Methods are essential for creating objects that can perform actions and interact with their own data. #JavaScript #WebDev #Frontend #JS #professional #career #development
To view or add a comment, sign in
-
-
Day 7: First-Class Functions, Function Statement, Function Expression & Anonymous Functions (JavaScript) JavaScript treats functions as first-class citizens. But what does that actually mean? 🔹 1️⃣ First-Class Functions In JavaScript, functions can: ✅ Be assigned to a variable ✅ Be passed as arguments ✅ Be returned from another function function greet() { return "Hello"; } function execute(fn) { console.log(fn()); } execute(greet); 👉 This ability makes concepts like callbacks, closures, and higher-order functions possible. 🔹 2️⃣ Function Statement (Function Declaration) function add(a, b) { return a + b; } ✔️ Hoisted completely ✔️ Can be called before definition 🔹 3️⃣ Function Expression const add = function(a, b) { return a + b; }; ✔️ Treated like a variable ❌ Not fully hoisted (lives in Temporal Dead Zone if let/const) 🔹 4️⃣ Anonymous Function A function without a name. setTimeout(function() { console.log("Hello"); }, 1000); 👉 Usually used in function expressions or callbacks. 🧠 Mental model to remember 🔥 Key Difference (Interview Favorite) Function Statement → Hoisted with definition Function Expression → Hoisted as variable (undefined / TDZ) Anonymous → No function name First-Class Function → Ability, not a type #Javascript #FirstClassFunction #FunctionExpression #FunctionStatement #AnonymousFunction #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 6 Not Just Motivation — Real Concepts to Build Strong Technical Understanding (Part 6) This keyword in JavaScript (a small concept, big impact) In JavaScript, this is a reference to the object that is executing the current function. Its value is decided at runtime, based on how a function is called, not where it is defined. Let’s see a classic real-world case where this behaves differently setTimeout with arrow function const user = { name: "Vicky", greet() { setTimeout(() => { console.log(this.name); }, 0); }, }; user.greet(); Output:Vicky Why? Arrow functions do not have their own this They capture this from the surrounding (lexical) scope Surrounding scope here is greet() greet() is called as user.greet() So this === user For better intuition, think of it like this (pseudo model 👇): // not real JS code const _this = this; // this === user setTimeout(() => { console.log(_this.name); }); The arrow function simply remembers this. --------------------------------------------------------- setTimeout with normal function const user = { name: "Vicky", greet() { setTimeout(function () { console.log(this.name); }, 0); }, }; user.greet(); Output:undefined Why? setTimeout executes the callback as a plain function Plain function call → no object on the left side So this defaults to: window (browser) undefined (strict mode) window.name is usually empty → undefined Mental model to remember Normal function: “Who called me?” Arrow function: “Where was I created?” This one distinction explains most this bugs in JavaScript. Have you ever been confused by this inside callbacks? Comment YES or NOW CLEAR #javascript #thiskeyword #frontend #softwareengineering
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
-
JavaScript Metaprogramming: The Power of Proxy & Reflect 🛡️✨ If you have ever wondered how 𝐕𝐮𝐞 𝟑 makes data reactive or how libraries perform magic validation under the hood, the answer usually lies in two powerful features: 𝐏𝐫𝐨𝐱𝐲 and 𝐑𝐞𝐟𝐥𝐞𝐜𝐭. Think of them as the dynamic duo of JavaScript object manipulation. 1️⃣𝐏𝐫𝐨𝐱𝐲: 𝐓𝐡𝐞 𝐆𝐚𝐭𝐞𝐤𝐞𝐞𝐩𝐞𝐫 👮♂️ A `Proxy` wraps your object and acts as a 𝐦𝐢𝐝𝐝𝐥𝐞𝐰𝐚𝐫𝐞 𝐥𝐚𝐲𝐞𝐫. • Before you read a property (`get`), write to it (`set`), or delete it, the Proxy intercepts the request. • 𝐔𝐬𝐞 𝐢𝐭 𝐟𝐨𝐫: Validation (checking types before setting), Security (hiding private properties), or Logging (debugging changes). 2️⃣𝐑𝐞𝐟𝐥𝐞𝐜𝐭: 𝐓𝐡𝐞 𝐒𝐭𝐚𝐧𝐝𝐚𝐫𝐝 𝐄𝐧𝐠𝐢𝐧𝐞 ⚙️ If `Proxy` is the interceptor, `Reflect` is the 𝐞𝐱𝐞𝐜𝐮𝐭𝐨𝐫. • It provides a standardized way to perform the actual operation on the original object. • 𝐖𝐡𝐲 𝐮𝐬𝐞 𝐢𝐭? Instead of manually trying to reproduce the default behavior (which can get messy), `Reflect.set(...)` ensures the operation runs safely and predictably, returning `true` or `false` for success. 🚀 𝐓𝐡𝐞 𝐁𝐞𝐬𝐭 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐞 𝐏𝐚𝐭𝐭𝐞𝐫𝐧: Intercept with `Proxy` ➡️ Add your custom logic ➡️ Execute default behavior with `Reflect`. 𝐑𝐞𝐚𝐥-𝐖𝐨𝐫𝐥𝐝 𝐒𝐮𝐩𝐞𝐫𝐩𝐨𝐰𝐞𝐫𝐬: ✅ 𝐑𝐞𝐚𝐜𝐭𝐢𝐯𝐢𝐭𝐲 𝐄𝐧𝐠𝐢𝐧𝐞𝐬 (Vue 3, MobX) ✅ 𝐒𝐦𝐚𝐫𝐭 𝐕𝐚𝐥𝐢𝐝𝐚𝐭𝐢𝐨𝐧 (Forms that check themselves) ✅ 𝐀𝐏𝐈 𝐂𝐥𝐢𝐞𝐧𝐭𝐬 (Auto-injecting auth tokens) Check out the visual breakdown below! 👇 Have you used `Proxy` in production, or does it still feel like "library-author territory" to you? #JavaScript #WebDevelopment #Metaprogramming #VueJS #ReactJS #SoftwareEngineering #CodingTips
To view or add a comment, sign in
-
-
🚀 JavaScript Topics Every Frontend Developer Should Master JavaScript is more than just a scripting language — it’s the backbone of modern web development. If you’re serious about frontend growth, these core JS topics are non-negotiable 🔹 Basics & Fundamentals • var, let, const • Data types & operators • Type coercion 🔹 Functions & Scope • Function declarations vs expressions • Arrow functions • Lexical scope • Closures 🔹 Objects & Arrays • Object methods • Destructuring • Spread & Rest operators • Shallow vs Deep Copy 🔹 Asynchronous JavaScript • Callbacks • Promises • async / await • Event Loop 🔹 DOM & Events • DOM traversal • Event bubbling & capturing • Event delegation 🔹 Advanced Concepts • Hoisting • this keyword • Prototype & inheritance • Currying • Debounce & Throttle 💡 Pro Tip: Understanding how JavaScript works internally will make frameworks like React, Vue, or Angular much easier to master. 📌 Keep learning. Keep building. Keep improving. #JavaScript #FrontendDevelopment #WebDevelopment #UIDeveloper #ReactJS #LearningJourney #Programming
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗕𝗮𝘀𝗶𝗰𝘀 𝗢𝗳 𝗥𝗲𝗮𝗰𝘁 You want to build efficient frontend applications. React is a JavaScript library that helps you do this. Before React, updating a webpage was messy. You had to manually change the DOM, which was tedious and hard to scale. React compares the old and new virtual DOM and renders only the changes when you update a state. Let's start with the basics: - Components are reusable code segments that return JSX. - JSX is a syntax extension for JavaScript that lets you write HTML-like code in a JavaScript file. - A component can only return one JSX tag, so you need to wrap multiple tags in a container. - Props help components interact with each other by passing parameters. - State is a component's memory, which changes when you interact with it. - Hooks like useState, useContext, and useRef help you manage state and references. You can also create your own hooks. When you build a component, you need to export it so it can be used in other files. React's main job is rendering, but it also handles side effects like fetching data or updating the page title. The useEffect Hook helps you do this. It runs after React finishes rendering and keeps your UI logic clean. You can control when the effect runs by using a dependency array. This is a basic intro to React. You need to learn more to become proficient. Source: https://react.dev/learn
To view or add a comment, sign in
-
🚀 JavaScript Hoisting: A Practical Breakdown Hoisting describes how JavaScript processes declarations before code execution. What actually gets hoisted — and how — depends on the type of declaration, which is why different keywords behave differently. 🔹 Function Declarations Function declarations are fully hoisted, so they can be called before they appear in the code. greet(); // Works function greet() { console.log("Hello!"); } 🔹 var Variables var declarations are hoisted, but their values are not. Before assignment, the variable is undefined. console.log(count); // undefined var count = 3; 🔹 let Variables let is hoisted but placed in the Temporal Dead Zone (TDZ). Accessing it before declaration throws an error. console.log(total); // ReferenceError let total = 10; 🔹 const Variables const behaves like let in terms of hoisting and TDZ, but its value cannot be reassigned. console.log(rate); // ReferenceError const rate = 5; 🔹 Function Expressions & Arrow Functions These are hoisted only as variables, not as functions. sayHi(); // TypeError const sayHi = () => { console.log("Hi!"); }; #JavaScript #Hoisting #WebDevelopment #Frontend #CleanCode #Developers
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
In such case it’s much better to use groupBy() from Lodash (or similar library). This way it becomes: const usersByStatus = groupBy(users, "status”); const activeUsers = usersByStatus["active"]; Much more concise and flexible.