JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)
What is the difference between map and forEach functions?
Both map and forEach functions are used to iterate over an arrays but there are some differences in their functionality.
- Returning values: The
mapmethod returns a new array with transformed elements whereasforEachmethod returnsundefinedeven though both of them are doing the same job.
javascript
const arr = [1, 2, 3, 4, 5];
arr.map(x => x * x); // [1, 4, 9, 16, 25]
arr.forEach(x => x * x); //
The `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`
- Chaining methods: The
mapmethod is chainable. i.e, It can be attached withreduce,filter,sortand other methods as well. WhereasforEachcannot be attached with any other methods because it returnsundefinedvalue.
javascript
const arr = [1, 2, 3, 4, 5];
arr.map((x) => x * x).reduce((total, cur) => total + cur); // 55
arr.forEach((x) => x * x).reduce((total, cur) => total + cur); //Uncaught TypeError: Cannot read properties of undefine(reading 'reduce')
- Mutation: The
mapmethod doesn't mutate the original array by returning new array. WhereasforEachmethod 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.