Use .map() for creation, .forEach() for execution in JavaScript

Here is the golden rule: Use .forEach() when you want to DO something. (Like logging to the console or pushing to an external array). It returns undefined. Use .map() when you want to CREATE something new. It returns a brand new array of the same length. JavaScript const numbers = [1, 2, 3]; // ❌ Bad: Using map just to loop (creates an unused array in memory) numbers.map(num => console.log(num)); // ✅ Good: Using map in React to create an array of JSX elements const UI = numbers.map(num => <li key={num}>{num}</li>); Understanding this difference is crucial for writing clean, bug-free components! #JavaScript #ReactJS #CodingLife #WebDevelopment #Programming #LearnToCode

  • No alternative text description for this image

"Bad: Using map just to loop (creates an unused array in memory)" that's make it sound like there is an unused array hanging around, but that's not the case. the GC is removing it after. I prefer map for chaining and break up a potential big foreach into smaller filter and /or map

Exactly. I think the real distinction is side effects versus transformation. forEach is for performing actions, while map is for producing a new value, and that difference matters a lot for readable React code.

See more comments

To view or add a comment, sign in

Explore content categories