💡JavaScript/React Tip💡 Using an 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 the 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 Reduce Method for Efficient User Grouping
More Relevant Posts
-
🚀 What is filter() in JavaScript? (Complete Guide for Developers) In JavaScript, filter() is a powerful array method used to create a new array by selecting elements that meet a specific condition. It does not modify the original array — instead, it returns a new filtered array. 📌 Syntax: array.filter((element, index, array) => { return condition; }); element → Current item being processed index (optional) → Index of the current element array (optional) → The original array 🔎 Simple Example: const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // Output: [2, 4, 6] 👉 Here, filter() returns only the numbers divisible by 2. 📦 Real-World Example (Filtering Objects): const users = [ { name: "Ali", active: true }, { name: "Sara", active: false }, { name: "Ahmed", active: true } ]; const activeUsers = users.filter(user => user.active); console.log(activeUsers); ✅ This is commonly used in: Search functionality Product filtering (e-commerce) Dashboard data filtering Status-based filtering 💡 Important Points: ✔ filter() does not change the original array ✔ It always returns a new array ✔ If no element matches → returns an empty array ✔ It works great with arrow functions 🆚 Difference from map() and forEach(): map() → transforms every element filter() → selects elements based on condition forEach() → executes logic but returns nothing 🎯 Why Every Developer Should Master filter(): Because modern web apps rely heavily on dynamic data manipulation — and filter() makes your code cleaner, readable, and functional-programming friendly. Clean code + Functional methods = Better performance & maintainability ✨ Are you using filter() in your projects? Drop your favorite use case below 👇 #JavaScript #FrontendDevelopment #WebDevelopment #Coding #100DaysOfCode
To view or add a comment, sign in
-
𝗘𝗿𝗿𝗼𝗿 𝗣𝗿𝗼𝗽𝗮𝗴𝗮𝘁𝗶𝗼𝗻 𝗪𝗶𝗍𝗵 𝗖𝗎𝘀𝘁𝗼𝗺 𝗘𝗿𝗿𝗼𝗿 𝗧𝘆𝗽𝗲𝘀 Error handling is a key part of JavaScript development. You need to handle errors well to avoid unexpected behavior in your applications. Here are some ways to handle errors: - Create custom error classes to give more context to your errors - Use try/catch blocks to catch and handle errors - Handle errors in asynchronous code using async/await or .catch() blocks You can create custom error classes by extending the built-in Error class. For example: ```javascript class CustomError extends Error { constructor(message, code) { super(message); this.name = this.constructor.name; this.code = code; Error.captureStackTrace(this, this.constructor); } } ``` You can use these custom error classes to throw errors with more context. For example: ```javascript function riskyFunction() { throw new CustomError("Something went wrong!", 500); } ``` You can also add more properties to your custom error classes to give even more context. For example: ```javascript class DetailedError extends Error { constructor(message, code, details) { super(message); this.name = this.constructor.name; this.code = code; this.details = details; Error.captureStackTrace(this, this.constructor); } } ``` When working with promises, you need to handle errors carefully to avoid losing the error context. You can use .catch() blocks to catch and handle errors in promise chains. To improve your error handling, you can use logging libraries like winston or bunyan. These libraries allow you to log errors with context, making it easier to debug your applications. Remember to always handle errors in your asynchronous code to avoid uncaught promise rejections. You can use try/catch blocks or .catch() blocks to catch and handle errors. Source: https://lnkd.in/dQzv3DkF
To view or add a comment, sign in
-
𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝗸𝘀 𝗮𝗻𝗱 𝗠𝗮𝗰𝗿𝗼𝘁𝗮𝗸𝘀: 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 𝗗𝗲𝗺𝘆𝘀𝘁𝗶𝗳𝗶𝗲𝗱 You need to understand how JavaScript's event loop works. It helps you manage tasks and events in a non-blocking way. This is crucial for senior developers working on complex web applications. When a JavaScript program runs, it goes through a series of tasks. These tasks can be user interactions, network requests, timers, or promises. There are two types of tasks: macrotasks and microtasks. - Macrotasks include: - setTimeout - setInterval - I/O operations - Microtasks include: - Promise callbacks - Mutation Observers The event loop executes these tasks in a specific order. It runs a macrotask, then all the microtasks queued during that macrotask, until the microtask queue is empty. This means microtasks can interrupt macrotasks. Here's an example: ```javascript console.log('Start'); setTimeout(() => { console.log('Macrotask 1 completed'); }, 0); Promise.resolve().then(() => { console.log('Microtask 1 completed'); }); setTimeout(() => { console.log('Macrotask 2 completed'); }, 0); Promise.resolve().then(() => { console.log('Microtask 2 completed'); }); console.log('End'); ``` The output will be: ``` Start End Microtask 1 completed Microtask 2 completed Macrotask 1 completed Macrotask 2 completed ``` This shows that microtasks are completed before macrotasks. Understanding microtasks and macrotasks is vital for writing reliable and performant code. You can use them to ensure critical code executes immediately after the current task finishes. However, overusing microtasks can introduce performance issues. To optimize performance, ensure heavy computations reside within macrotasks. Use debouncing and throttling strategies for repetitive async calls. For further learning, check out: MDN Web Docs on Promises HTML Living Standard: The Event Loop JavaScript: The Definitive Guide Source: https://lnkd.in/gk_rM4Ur
To view or add a comment, sign in
-
𝗙𝗨𝗡𝗖𝗧𝗜𝗢𝗡 𝗖𝗨𝗥𝗥𝗬𝗜𝗡𝗚 𝗔𝗡𝗗 𝗣𝗔𝗥𝗧𝗜𝗔𝗟 𝗔𝗣𝗣𝗟𝗜𝗖𝗔𝗧𝗜𝗢𝗡 You want to write better JavaScript code. Function currying and partial application can help. These concepts come from functional programming. They help you design and structure your code. Currying breaks down a function that takes multiple arguments into a sequence of functions. Each function takes a single argument. This helps with modularization and reuse. - It transforms a function of arity n into n functions of arity 1. - It enables a high degree of modularization and reuse. Partial application fixes a function's arguments. It creates a new function with fewer arguments. - It allows you to fix a function's arguments. - It creates a new function with fewer arguments. Here's an example of currying: ```javascript function multiply(a) { return function(b) { return a * b; }; } ``` You can use it like this: ```javascript const double = multiply(2); console.log(double(5)); // Output: 10 ``` Partial application is similar. You can use it to fix some arguments and create a new function. These techniques have pros and cons: - Currying: improved modularization, potential performance overhead - Partial Application: enhanced flexibility, potential complexity You can use these techniques in different situations: - Configuration settings - Event handling - API calls However, there are potential pitfalls: - Over-currying - Unintentional overwrites - Debugging challenges To debug, you can use: - Stack traces - Browser developer tools - TypeScript Function currying and partial application are powerful techniques. They can help you write better JavaScript code. But you need to understand their mechanisms and implications. Source: https://lnkd.in/gkeqbpsE
To view or add a comment, sign in
-
𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝗸𝘀 𝗮𝗻𝗱 𝗠𝗮𝗰𝗿𝗼𝘁𝗮𝗸𝘀: 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 𝗗𝗲𝗺𝘆𝘀𝘁𝗶𝗳𝗶𝗲𝗱 You need to understand how JavaScript's event loop works. It helps you manage tasks and events in a non-blocking way. This is crucial for senior developers working on complex web applications. When a JavaScript program runs, it goes through a series of tasks. These tasks can be user interactions, network requests, timers, or promises. There are two types of tasks: macrotasks and microtasks. - Macrotasks include: - setTimeout - setInterval - I/O operations - Microtasks include: - Promise callbacks - Mutation Observers The event loop executes these tasks in a specific order. It runs a macrotask, then all the microtasks queued during that macrotask, until the microtask queue is empty. This means microtasks can interrupt macrotasks. Here's an example: ```javascript console.log('Start'); setTimeout(() => { console.log('Macrotask 1 completed'); }, 0); Promise.resolve().then(() => { console.log('Microtask 1 completed'); }); setTimeout(() => { console.log('Macrotask 2 completed'); }, 0); Promise.resolve().then(() => { console.log('Microtask 2 completed'); }); console.log('End'); ``` The output will be: ``` Start End Microtask 1 completed Microtask 2 completed Macrotask 1 completed Macrotask 2 completed ``` This shows that microtasks are completed before macrotasks. Understanding microtasks and macrotasks is vital for writing reliable and performant code. You can use them to ensure critical code executes immediately after the current task finishes. However, overusing microtasks can introduce performance issues. To optimize performance, ensure heavy computations or rendering logic reside within macrotasks. Use debouncing and throttling strategies for repetitive async calls. For further learning, check out: MDN Web Docs on Promises HTML Living Standard: The Event Loop JavaScript: The Definitive Guide Source: https://lnkd.in/gk_rM4Ur
To view or add a comment, sign in
-
JSX is NOT HTML. It’s JavaScript in Disguise. 🎭⚛️ When you start learning React, JSX feels like magic. You are writing HTML... inside a JavaScript function? But under the hood, it’s not HTML at all. 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐚𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐡𝐚𝐩𝐩𝐞𝐧𝐢𝐧𝐠? Browsers don't understand JSX. Before your code hits the browser, tools like 𝐁𝐚𝐛𝐞𝐥 transform that "HTML" into standard JavaScript objects. 𝐓𝐡𝐞 𝐓𝐫𝐚𝐧𝐬𝐟𝐨𝐫𝐦𝐚𝐭𝐢𝐨𝐧 𝐅𝐥𝐨𝐰: 1️⃣ You write: `<div className="box">Hello</div>` 2️⃣ Babel compiles it to: `React.createElement('div', { className: 'box' }, 'Hello')` 3️⃣ React turns that into a lightweight JS object (Virtual DOM). 4️⃣ Finally, React updates the real DOM. 𝐖𝐡𝐲 𝐢𝐬 𝐉𝐒𝐗 𝐬𝐭𝐫𝐢𝐜𝐭𝐞𝐫 𝐭𝐡𝐚𝐧 𝐇𝐓𝐌𝐋? Ever got an error for leaving a tag unclosed or using `class` instead of `className`? Since JSX becomes JavaScript function calls: • `class` is a reserved word in JS ➔ so we use `className`. • Function arguments must be well-defined ➔ so every tag must close. 𝐓𝐡𝐞 𝐏𝐨𝐰𝐞𝐫 𝐌𝐨𝐯𝐞: Because it is JavaScript, you can embed logic directly: `{ isLoggedIn ? <Dashboard /> : <Login /> }` Check out the visual breakdown below to see the full journey from JSX to DOM! 👇 Do you prefer writing JSX, or have you ever tried writing raw `React.createElement` code (just for fun)? 😅 #ReactJS #WebDevelopment #Frontend #JavaScript #JSX #CodingBasics #Babel
To view or add a comment, sign in
-
-
**JavaScript Closures Demystified: No More Anxiety!** If you’ve ever felt your heart skip a beat when someone mentions “closures” in JavaScript, you’re not alone. Many developers find the concept intimidating—but it doesn’t have to be. In simple terms, a **closure** is a function that “remembers” the variables from its outer scope, even after that outer function has finished running. Think of it like a backpack: when a function is created, it carries a snapshot of the environment it was born in. Why does this matter? - **Data Privacy**: Closures help create private variables that can’t be accessed from outside. - **State Preservation**: They’re essential in callbacks, event handlers, and functional programming patterns. - **Modular Code**: Enable patterns like the Module Pattern, keeping your code organized and secure. Example snippet: ```javascript function createCounter() { let count = 0; return function() { count++; console.log(count); }; } const counter = createCounter(); counter(); // 1 counter(); // 2 // `count` is protected, accessible only via the returned function. ``` Closures aren’t magic—they’re a natural part of how JavaScript handles scope. Once you grasp the idea of “functions with memories,” a lot of advanced JS patterns start to make sense. So next time you hear “closure,” take a deep breath. It’s just a function carrying its little backpack of variables. #JavaScript #WebDevelopment #CodingTips #LearnToCode #SoftwareEngineering
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗦𝗲𝗰𝗿𝗲𝘁 𝗧𝗼 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 You write JavaScript code and it doesn't work as expected. You think it's a bug, but it's not. It's how JavaScript works. Let's look at an example: ```javascript const user = { name: "Alice", role: "user" }; const admin = user; admin.role = "admin"; console.log(user.role); // "admin" ``` You might expect "user", but you get "admin". This happens because `admin` and `user` point to the same object. Here's what's happening: - The Stack is like a temporary order board. It holds function calls, variables, and pointers. - The Heap is like a storage room. It holds objects, arrays, and functions. When you write `const user = { name: "Alice" }`, JavaScript does this: ``` STACK HEAP ┌─────────────┐ ┌──────────────────┐ │ user: ──────┼────────>│ { │ └─────────────┘ │ name: "Alice" │ │ } │ └──────────────────┘ ``` The variable `user` lives on the stack and holds a pointer to the object on the heap. When you copy a variable, you copy the pointer, not the object. So, `admin` points to the same object as `user`. To fix this, you can create a new object: ```javascript const user = { name: "Alice", role: "user" }; const admin = { ...user }; admin.role = "admin"; console.log(user.role); // "user" ``` Now, `admin` points to a new object, and changing it doesn't affect `user`. This understanding is crucial when working with React state or any code that depends on detecting changes in objects. Source: https://lnkd.in/gfUaubUy
To view or add a comment, sign in
-
⚔️ Normal JavaScript vs. War‑Style JavaScript What works locally often breaks in production. Here’s how to tell the difference—and why it matters. 🧪 Normal JavaScript You write it in a sandbox. The data is clean, the network is fast, and the user follows the happy path. ✅ No null or undefined to worry about ✅ Async/await with no .catch() ✅ const user = data.user.profile.email; – works every time This is lab‑grade code. Great for prototypes. Dangerous in production. 🛡️ War‑Style JavaScript This code has seen things. It’s been through code reviews, pentesting, and a 3am outage. 🔹 Defensive reading const email = data?.user?.profile?.email ?? 'fallback@example.com'; 🔹 Error handling that actually handles try { await riskyCall(); } catch (err) { logger.error(err); // Recover, don’t just crash } 🔹 Input validation – never trust the client 🔹 Performance under load – debouncing, throttling, memoization 🔹 Security – escape user input, validate JWTs, use Helmet.js 🔹 Observability – logs, metrics, structured errors War‑style code assumes the worst: 📉 Network fails 🧨 Third‑party API changes shape 🐞 Users type “eval()” into a text box 📈 The Real Difference Normal JS War‑Style JS Works on my machine Works for 10k concurrent Throws undefined Shows a friendly error One developer knows it Handover‑ready, documented “It’s fine for now” “How will this scale?” 🔥 Why This Matters War‑style isn’t over‑engineering—it’s respect. Respect for your users, your future self, and the people who will maintain your code. Start by auditing your last PR. Did you handle the unhappy paths? Did you log failures? Did you assume nothing? Normal JavaScript gets the job done. War‑style JavaScript keeps the job done. 💬 What’s one “war‑style” habit you always practice? I’ll go first: optional chaining and nullish coalescing are non‑negotiable. 👇
To view or add a comment, sign in
-
Day 14/30 – Cancelable Function with Timeout in JavaScript Challenge ⏳❌ | Async 💻🚀 🧠 Problem: Create a function that: Delays execution of fn by t milliseconds Returns a cancel function (cancelFn) If cancelFn is called before the delay ends → execution is canceled If not canceled → fn runs with the given arguments ✨ What this challenge teaches: Timer management using setTimeout Cancellation patterns in async JavaScript Controlling execution flow — a key skill for real-world apps This concept is used in: ⚡ Debouncing & throttling ⚡ API request cancellation ⚡ User interaction handling ⚡ Performance optimization Example 1: Input: fn = (x) => x * 5, args = [2], t = 20 Output: [{"time": 20, "returned": 10}] Explanation: const cancelTimeMs = 50; const cancelFn = cancellable((x) => x * 5, [2], 20); setTimeout(cancelFn, cancelTimeMs); The cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened after the execution of fn(2) at 20ms. Constraints: fn is a function args is a valid JSON array 1 <= args.length <= 10 20 <= t <= 1000 10 <= cancelTimeMs <= 1000 💬 Where would you use cancelable logic in a real project? #JavaScript #30DaysOfJavaScript #CodingChallenge #AsyncJavaScript #Closures #JSLogic #LeetCode #WebDevelopment #LearnToCode #CodeEveryday #DeveloperJourney #Programming #TechCommunity JavaScript cancelable function setTimeout cancel execution Async function cancellation JS JavaScript debounce logic LeetCode JavaScript solution JS interview questions Advanced JavaScript concepts Daily coding challenge
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