JavaScript map() Misuse: Why Developers Go Wrong

Most Developers Misuse map() in JavaScript — Here’s Why It Matters I often review Angular / React code where I see this users.map(user => {  console.log(user.name); }); This is a code smell. Why? Because map() is NOT meant for side effects. ✅ What map() is ACTUALLY for map() is used to transform data and return a new array. const userNames = users.map(user => user.name); ✔ Clear intent ✔ Immutable ✔ Chainable ✔ Functional style ❌ Common Mistake Developers Make Using map() instead of forEach() when: No new array is needed Only logging / mutation / API calls are happening Returned value is ignored This leads to: Confusing code Wasted memory Wrong mental model ✅ When forEach() is the RIGHT choice Use forEach() for side effects only: users.forEach(user => { console.log(user.name); }); ✔ Intent is clear ✔ No unnecessary array creation Real Production Bug I’ve Seen Using forEach() with async code users.forEach(async user => { await saveUser(user); }); console.log("Done"); // Executes too early ✅ Correct approach: await Promise.all( users.map(user => saveUser(user)) ); Simple Rule to Remember map = transform data forEach = side effects If you’re not using the returned array → don’t use map().

To view or add a comment, sign in

Explore content categories