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.
| Feature | map() | forEach() |
|---|---|---|
| Use case | Transforming data | Performing side effects per element |
| Chainable | Yes (.map().filter().reduce()) | No (returns undefined) |
| Performance | Slightly slower (creates new array) | Slightly faster (no new array) |
| Return value | New array with transformed elements | undefined |
| Side effects | Should not have side effects | Expected to have side effects |
| Original array | Not modified | Not 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
Related Tutorials
Related Glossary Terms
A function passed as an argument to another function, to be executed later. Callbacks are the foundation of asynchronous JavaScript and are used extensively in event handling and array methods.
Higher-Order FunctionA function that either takes one or more functions as arguments, returns a function, or both. Common examples include map, filter, reduce, and forEach.
Array MethodsBuilt-in methods on the Array prototype for transforming and querying arrays. Key methods include map (transform each element), filter (select elements), reduce (accumulate), find (first match), some/every (boolean tests), and sort.