map() vs forEach() in JavaScript

Both iterate over arrays, but they serve different purposes. Understanding when to use each is key to writing clean functional JavaScript.

Featuremap()forEach()
Use caseTransforming dataPerforming side effects per element
ChainableYes (.map().filter().reduce())No (returns undefined)
PerformanceSlightly slower (creates new array)Slightly faster (no new array)
Return valueNew array with transformed elementsundefined
Side effectsShould not have side effectsExpected to have side effects
Original arrayNot modifiedNot modified

Verdict

Use map() when you need to transform data into a new array. Use forEach() when you need to perform side effects (logging, DOM updates, API calls) for each element.

Code Example

Javascript
Tip: Modify the code above and click “Run” to see the results

Related Tutorials

Related Glossary Terms