Understanding Reduce() Output with JavaScript

🌙 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

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories