🌙 Evening Post — Understanding This reduce() Output Clearly This morning’s code was: const result = [1, 2, 3].reduce((acc, curr) => { return acc + curr * 2; }, 0); console.log(result); 💡 Correct Output 12 Now let’s understand why 👇 🧠 Simple Explanation : 🔹 Step 1: Initial value }, 0); acc starts with 0 🔹 Step 2: How reduce() works reduce() runs one element at a time, carrying the result forward. Expression used every time: acc + curr * 2 ⚠️ Important: 👉 Multiplication happens before addition (* has higher precedence than +) 🔹 Step-by-step calculation Array: [1, 2, 3] 1️⃣ First iteration acc = 0 curr = 1 acc + curr * 2 0 + (1 * 2) = 2 2️⃣ Second iteration acc = 2 curr = 2 2 + (2 * 2) = 6 3️⃣ Third iteration acc = 6 curr = 3 6 + (3 * 2) = 12 🎯 Final Result 12 🎯 Key Takeaways : reduce() works left to right acc carries the result forward Operator precedence matters inside reduce curr * 2 runs before acc + 📌 Many wrong answers come from doing: (acc + curr) * 2 ❌ But JavaScript actually does: acc + (curr * 2) ✅ 💬 Your Turn Did you calculate it step by step or mentally? 😄 Comment “Step by step 👍” or “Did it in my head 😅” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment
Understanding Reduce() Output with JavaScript
More Relevant Posts
-
Evening Post — Why includes() Works but indexOf() Fails Here This morning’s code was: const arr = [1, 2, NaN, 4]; console.log(arr.includes(NaN)); console.log(arr.indexOf(NaN)); 💡 Correct Output true -1 Yes — same value, same array, different results 😄 Let’s understand why. 🧠 Simple Explanation : 🔹 includes() uses SameValueZero comparison That means: It can correctly compare NaN It treats NaN as equal to NaN So: arr.includes(NaN) ✔ Finds NaN ✔ Returns: true 🔹 indexOf() uses strict equality (===) Important rule 👇 👉 In JavaScript: NaN === NaN // false So when indexOf() checks each element: It compares NaN === NaN That comparison always fails Because of this: arr.indexOf(NaN) ❌ Cannot find NaN ✔ Returns: -1 🎯 Key Takeaways : includes() can find NaN indexOf() cannot find NaN NaN is the only value that is not equal to itself Prefer includes() for value checks 📌 This difference has caused real production bugs. 💬 Your Turn Did you expect both lines to behave the same? 😄 Comment “Surprising 😮” or “Knew this 👍” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
Evening Post — Why includes() Works but indexOf() Fails Here This morning’s code was: const arr = [1, 2, NaN, 4]; console.log(arr.includes(NaN)); console.log(arr.indexOf(NaN)); 💡 Correct Output true -1 Yes — same value, same array, different results 😄 Let’s understand why. 🧠 Simple Explanation : 🔹 includes() uses SameValueZero comparison That means: It can correctly compare NaN It treats NaN as equal to NaN So: arr.includes(NaN) ✔ Finds NaN ✔ Returns: true 🔹 indexOf() uses strict equality (===) Important rule 👇 👉 In JavaScript: NaN === NaN // false So when indexOf() checks each element: It compares NaN === NaN That comparison always fails Because of this: arr.indexOf(NaN) ❌ Cannot find NaN ✔ Returns: -1 🎯 Key Takeaways : includes() can find NaN indexOf() cannot find NaN NaN is the only value that is not equal to itself Prefer includes() for value checks 📌 This difference has caused real production bugs. 💬 Your Turn Did you expect both lines to behave the same? 😄 Comment “Surprising 😮” or “Knew this 👍” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
🌙 Evening Post — Explanation & Answer ✅ Why This Map Has Two Entries This morning’s code was: const map = new Map(); map.set({}, "first"); map.set({}, "second"); console.log(map.size); 💡 Correct Output 2 Yes — two entries, not one 😄 Here’s why 👇 🧠 Simple Explanation : 🔹 Objects are compared by reference, not by value Even though both keys look like {}: {} !== {} Each {} creates a new object in memory. So JavaScript sees this as: Key 1 → one object reference Key 2 → another object reference They are completely different keys. 🔹 How Map works Map allows any type as a key Keys are matched by reference Different object references → different entries So: map.size // 2 🎯 Key Takeaways : Map keys are compared by reference {} and {} are never the same key Objects are not value-equal by default This behavior is different from plain objects 📌 To use the same key, you must reuse the same reference: const key = {}; map.set(key, "first"); map.set(key, "second"); 💬 Your Turn Did you expect the size to be 1 or 2? 😄 Comment “Got it wrong 😅” or “Knew this 👍” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #Maps #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
🚀 LeetCode: 3Sum The goal is to find all unique triplets in an array that sum up to zero. This is a significant step up from Two Sum, requiring careful handling of duplicates to ensure every triplet in the result is unique. 🛠️ My Approach Sorting for Strategy: I started by sorting the array in ascending order. This is crucial as it allows us to easily skip duplicate values and use a directional two-pointer technique. 🔡 Fixed Element Loop: I iterated through the array, treating each element as a potential first part of a triplet. To optimize, if the current element is greater than zero, I break the loop immediately since no combination of following positive numbers can sum to zero. 🧹 Two-Pointer Optimization: For each fixed element, I used two pointers—one starting just after the fixed element (l) and one at the very end (r). 📍 If the sum is too high, I move the right pointer in. If the sum is too low, I move the left pointer out. When a sum of zero is found, I capture the triplet and then skip any identical adjacent values to avoid duplicate results. ❌ This approach transforms a potential O(n^3) brute-force cubic time complexity into a much more efficient quadratic solution. 📊 Efficiency Analysis ⏱️ Time Complexity: O(n^2) due to the nested two-pointer search inside the main loop. 💾 Space Complexity: O(1) or O(n) depending on the implementation of the sorting algorithm, as we don't use extra data structures for the search itself. Achieving a 91.76% runtime beat on this classic problem! Handling edge cases and duplicates is where the real engineering happens. 🚀👨💻 #LeetCode #JavaScript #CodingLife #Algorithms #WebDevelopment #ProblemSolving #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
𝐓𝐞𝐦𝐩𝐨𝐫𝐚𝐥 𝐃𝐞𝐚𝐝 𝐙𝐨𝐧𝐞 𝐞𝐱𝐩𝐥𝐚𝐢𝐧𝐬 𝐰𝐡𝐲 𝐥𝐞𝐭 𝐚𝐧𝐝 𝐜𝐨𝐧𝐬𝐭 𝐝𝐨𝐧’𝐭 𝐛𝐞𝐡𝐚𝐯𝐞 𝐥𝐢𝐤𝐞 𝐯𝐚𝐫. For a long time, hoisting felt inconsistent to me. Variables seemed to exist before execution, yet accessing some of them caused errors while others didn’t. The confusion cleared once I stopped thinking only in terms of hoisting and started looking at 𝐦𝐞𝐦𝐨𝐫𝐲 𝐚𝐥𝐥𝐨𝐜𝐚𝐭𝐢𝐨𝐧. When JavaScript begins execution, it allocates memory before running any line of code. For var, this memory is allocated in the 𝐠𝐥𝐨𝐛𝐚𝐥 𝐬𝐜𝐨𝐩𝐞 and initialized with undefined. For let and const, memory is allocated in a 𝐬𝐞𝐩𝐚𝐫𝐚𝐭𝐞 𝐬𝐜𝐫𝐢𝐩𝐭 𝐦𝐞𝐦𝐨𝐫𝐲 𝐬𝐩𝐚𝐜𝐞, not the global one. This memory exists , but it’s 𝐧𝐨𝐭 𝐚𝐜𝐜𝐞𝐬𝐬𝐢𝐛𝐥𝐞 until initialization. That gap is the 𝐓𝐞𝐦𝐩𝐨𝐫𝐚𝐥 𝐃𝐞𝐚𝐝 𝐙𝐨𝐧𝐞 (𝐓𝐃𝐙). What helped this click: • TDZ is the time between 𝐡𝐨𝐢𝐬𝐭𝐢𝐧𝐠 𝐚𝐧𝐝 𝐢𝐧𝐢𝐭𝐢𝐚𝐥𝐢𝐳𝐚𝐭𝐢𝐨𝐧 • Accessing a variable inside TDZ throws a 𝐑𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐞𝐄𝐫𝐫𝐨𝐫 • TDZ prevents usage before a value is safely assigned • It’s different from 𝐒𝐲𝐧𝐭𝐚𝐱𝐄𝐫𝐫𝐨𝐫 and 𝐓𝐲𝐩𝐞𝐄𝐫𝐫𝐨𝐫 What changed my approach was realizing TDZ isn’t something to avoid — it’s something to design around. By placing declarations and initializations at the top of the scope, we effectively 𝐬𝐡𝐫𝐢𝐧𝐤 𝐭𝐡𝐞 𝐓𝐃𝐙 𝐰𝐢𝐧𝐝𝐨𝐰 𝐭𝐨 𝐳𝐞𝐫𝐨. Once initialization happens first, execution becomes predictable — and unexpected errors disappear. #JavaScript #SoftwareEngineering #ProblemSolving #DeveloperJourney #LearningInPublic #TechCommunity #ContinuousLearning
To view or add a comment, sign in
-
-
Pop quiz: Where does JavaScript store `const age = 25;` in memory? a) The stack b) The heap c) Depends on the engine and context d) I pretend to know but actually have no idea If you picked (c) or (d), congrats — you're thinking like an engineer. The truth? Modern engines like V8 are way more complex than "primitives = stack, objects = heap." But understanding that simplified mental model is still incredibly useful for grasping: → Why object comparisons behave the way they do → How references vs values work conceptually → Why closures "capture" variables I built an interactive visualizer that walks through this simplified model step-by-step, because sometimes you need to understand the map before you explore the territory. Try it here: https://lnkd.in/dtmd4U-G Yes, V8 does wild optimizations under the hood. No, you probably don't need to think about that while debugging why your object mutated unexpectedly.
To view or add a comment, sign in
-
-
Day 40 of me reading random and basic but important coding topicsss..... Today I read about event bubbling...... Event Bubbling is the process where an event starts at the most specific element (the target) and flows upward through its ancestors like a bubble rising in water. * The Flow: <td> → <tr> → <table> → <body> → window * The Mechanism: Most events (click, keydown, etc.) bubble by default. When the event triggers on the child, the browser checks the parent for a handler, executes it, and moves up. Why does this exist? Two words: Event Delegation. Instead of attaching 100 separate event listeners to 100 rows in a table (which is memory-expensive), we attach one listener to the parent <table>. * Logic is simple -: I don't care which row was clicked, I just care that the table was clicked..... * Trick is that:- We use event.target inside the parent handler to see exactly which child element triggered the event. Now let's see it's usefullness first..... 1. Memory Efficiency: One listener vs. thousands. This is a massive win for application memory usage, especially in Single Page Applications (SPAs) with large lists or infinite scrolls. 2. Dynamic Content: If you add new items to a list via AJAX, you don't need to attach new listeners. The parent is already listening. 3. Browser Load: Less time spent during the mounting phase of your components because the browser registers fewer bindings. Now the important cons which we usually avoid..... 1. The stopPropagation() Trap: We often use event.stopPropagation() to prevent parent handlers from firing. Risk: This creates a "Dead Zone." Analytics tools that listen on the document level to track user clicks will suddenly go blind to that part of your app. 2. Not Everything Bubbles: Events like focus, blur, and load do not bubble. (We have to use focusin / focusout or capture phase for those). 3. Deep Nesting Complexity: If your DOM is incredibly deep, an event bubbling all the way to the top technically takes CPU time, though in modern engines, this cost is negligible compared to the memory savings of delegation. Keep Learning!!!! #JavaScript #WebPerformance #FrontendDev #EventBubbling #SoftwareArchitecture
To view or add a comment, sign in
-
-
🌙 Evening Post — slice vs splice (Same Look, Different Behavior) This morning’s code was: let arr = [1, 2, 3, 4]; let a = arr.slice(1, 3); let b = arr.splice(1, 2); console.log(a); console.log(b); console.log(arr); 💡 Correct Output [2, 3] [2, 3] [1, 4] Yes — the first two lines look the same, but the array changes 👀 Let’s understand why. 🧠 Simple Explanation : 🔹 slice(start, end) Does NOT change the original array Returns a new array end index is not included arr.slice(1, 3) From [1, 2, 3, 4]: Takes index 1 and 2 Returns: [2, 3] Original arr is still: [1, 2, 3, 4] 🔹 splice(start, deleteCount) Changes the original array Removes elements Returns the removed elements arr.splice(1, 2) From [1, 2, 3, 4]: Removes 2 elements starting at index 1 Returns: [2, 3] Now the original array becomes: [1, 4] 🎯 Final Values a → [2, 3] b → [2, 3] arr → [1, 4] 🎯 Key Takeaways : slice() → non-mutating splice() → mutating slice uses end index splice uses delete count 📌 Many bugs happen because developers assume slice and splice are similar. 💬 Your Turn Which one surprised you more? 😄 Comment “slice 😮” or “splice 🤯” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
✅ Solved LeetCode: Binary Tree Postorder Traversal (145) Implemented an iterative Postorder Traversal in JavaScript using two stacks, following the sequence: Left → Right → Root. The strategy works as follows: - Use the first stack (s1) to process nodes in a modified preorder fashion (Root → Left → Right). - Push each popped node into a second stack (s2). - After traversal, pop nodes from s2 to get the correct Postorder sequence. This approach effectively simulates recursion while maintaining the correct traversal order. ⏱ Time Complexity: O(n) — each node is processed once 🧠 Space Complexity: O(n) — due to the use of two stacks A neat stack-based trick to achieve Postorder without recursion! 🌳
To view or add a comment, sign in
-
-
🚀 LeetCode: Two Sum II - Input Array Is Sorted The goal is to find two numbers in a 1-indexed sorted array that add up to a specific target sum. Since the array is already sorted, we can find the indices efficiently without extra storage. 🛠️ My Approach 1. Initialization: I used two pointers, i starting at the beginning (index 0) and j at the end of the array. 🔡 2. Sorted Property Leverage: Instead of a nested loop, I compared the sum of elements at i and j to the target. If the sum is too high, I decrement j; if it's too low, I increment i. 🧹 3. Two-Pointer Optimization: By narrowing the window from both sides, I found the exact pair in a single pass. 📍 4. One pointer moves from the start (i), and the other from the end (j). ❌ If the sum matches the target, we return the 1-indexed positions [i + 1, j + 1] and break the loop. 📊 Efficiency Analysis ⏱️ Time Complexity: O(n) 💾 Space Complexity: O(1) #LeetCode #JavaScript #CodingLife #Algorithms #WebDevelopment #ProblemSolving #SoftwareEngineering #TechCommunity
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