JavaScript forEach() Mistake: Why map() is the Correct Choice

🚀 A JavaScript forEach() Mistake At first glance, this looks correct: const numbers = [1, 2, 3, 4]; const result = numbers.forEach(num => num * 2); console.log(result); Expected: [2, 4, 6, 8] Actual output: undefined Why? Because forEach() does not return a new array. It only executes a function for each element. So result becomes undefined. If you want to transform data, use map(). ✅ Correct approach: const numbers = [1, 2, 3, 4]; const result = numbers.map(num => num * 2); console.log(result); Now the output is: [2, 4, 6, 8] Small difference in method. Big difference in behavior. In JavaScript, choosing the right array method matters more than the logic itself. What array method confused you the most when you started? #javascript #frontenddeveloper #webdevelopment #coding #softwareengineering

  • No alternative text description for this image

Array.forEach exists to fulfill the Iterable Interface. Array is not the only class that implements interable - Map does as does NodeCollection ( the return type of document.query.selectorAll() ). As a result forEach should only be used in cases where the object will be iterable but not necessarily an array.

I once ran into this exact issue while chaining array methods, forEach() silently broke the chain because it returns undefined. Since then I’ve tried to stick with map/filter pipelines for transformations and reserve forEach only for side effects

Like
Reply

With each method in javascript we can perform only operation on each array element, but with map we can return a New array manipulating to each element. Nice post

Like
Reply

I think there is a typo. They are both going to fail.  cosnt result = numbers. should be ; instead of . ^

Like
Reply

forEach() does not return any value, so the value of result becomes undefined.

Like
Reply

Knowledge like this helps many learners.

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories