👨‍💻 Enea Zani’s Post

𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗠𝗮𝗽() 𝘃𝘀 𝗙𝗼𝗿𝗘𝗮𝗰𝗵() 🔥 Confused about when to use map() and when to use forEach()? Here’s the difference that every JavaScript developer should know 👇 🔹 forEach() → executes a function for every element 🔹 It does NOT return a new array 🔹 Mainly used for side effects (logging, API calls, DOM updates) Example: ➡️ arr.forEach(item => console.log(item)) 🔹 map() → also loops through every element 🔹 BUT returns a brand new array 🔹 Perfect for transforming data Example: ➡️ const names = users.map(user => user.name) ⚠️ The common mistake: Using forEach() when you actually need transformed data 😬 Example: ❌ const result = arr.forEach(item => item * 2) Why? Because forEach() returns: ➡️ undefined Correct way: ✅ const result = arr.map(item => item * 2) 💡 Simple rule: Need a new array? ➡️ use map() Need to just “do something” with each item? ➡️ use forEach() That small difference can save you from weird bugs and messy code. 🚀 Understanding this = cleaner logic + better interviews + stronger JavaScript fundamentals If you're learning JS, React, or preparing for technical interviews… this is essential. 📚 Sources: • JavaScript Masteryw3schools.com Follow for more: 👨💻 Enea Zani #javascript #webdevelopment #frontend #reactjs #coding #developers #programming #100DaysOfCode #learnjavascript #softwareengineer

  • Difference between map() and forEach() function in javascript, visualised

To view or add a comment, sign in

Explore content categories