Advertisement
Both map and forEach functions are used to iterate over an arrays but there are some differences in their functionality.
1. Returning values: The map method returns a new array with transformed elements whereas forEach method returns undefined eventhough both of them are doing the same job.
1const arr = [1, 2, 3, 4, 5];
2
3arr.map(x => x * x); // [1, 4, 9, 16, 25]
4
5arr.forEach(x => x * x); //
6
7The `forEach()` method in JavaScript always returns undefined. This is because forEach() is used to iterate over arrays and perform side effects on each element, rather than returning a `new array or transforming the original array`2. Chaining methods: The map method is chainable. i.e, It can be attached with reduce, filter, sort and other methods as well. Whereas forEach cannot be attached with any other methods because it returns undefined value.
1const arr = [1, 2, 3, 4, 5];
2
3arr.map((x) => x * x).reduce((total, cur) => total + cur); // 55
4
5arr.forEach((x) => x * x).reduce((total, cur) => total + cur); //Uncaught TypeError: Cannot read properties of undefine(reading 'reduce')3. Mutation: The map method doesn't mutate the original array by returning new array. Whereas forEach method also doesn't mutate the original array but it's callback is allowed to mutate the original array.
Note: Both these methods existed since ES5 onwards.
Advertisement
JavaScript Coding Exercise 32
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement