Map vs forEach in JavaScript: Key Differences and Usage
map creates a new array by transforming each element, while forEach simply runs a function on each element without returning anything. Use map when you want a new array; use forEach for side effects like logging or updating external variables.Quick Comparison
Here is a quick side-by-side comparison of map and forEach methods in JavaScript.
| Feature | map | forEach |
|---|---|---|
| Return value | Returns a new array with transformed elements | Returns undefined (no return) |
| Purpose | Transforms each element and collects results | Performs an action on each element without collecting results |
| Chainable | Yes, returns an array so you can chain | No, returns undefined so cannot chain |
| Mutates original array | No, original array stays unchanged | No, original array stays unchanged |
| Use case | When you need a new array from existing one | When you want to run code for side effects only |
| Performance | Slightly slower due to creating new array | Slightly faster for simple side effects |
Key Differences
map is designed to transform each element of an array and return a new array with the transformed values. It does not change the original array but creates a new one based on the function you provide. This makes map ideal when you want to convert or modify data and keep the results.
On the other hand, forEach is used to execute a function on each element for its side effects, such as logging, updating external variables, or modifying objects outside the array. It does not return anything, so you cannot chain it or get a new array from it.
Because map returns a new array, it is chainable with other array methods like filter or reduce. forEach returns undefined, so chaining is not possible. Both methods do not mutate the original array unless you explicitly modify elements inside the callback.
Code Comparison
const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled);
forEach Equivalent
const numbers = [1, 2, 3, 4]; const doubled = []; numbers.forEach(num => { doubled.push(num * 2); }); console.log(doubled);
When to Use Which
Choose map when you want to create a new array by transforming each element of an existing array. It is perfect for data conversion and chaining multiple array operations.
Choose forEach when you only need to perform side effects like logging, updating external variables, or calling functions without needing a new array. It is simpler and slightly faster for these tasks.
Key Takeaways
map returns a new array with transformed elements; forEach returns undefined.map for data transformation and chaining; use forEach for side effects.map is slightly slower due to creating a new array; forEach is faster for simple iteration.