Difference Between map() and forEach() Methods in JavaScript?

In this article, we will discuss .map() and forEach() methods of javascript and also go through the differences between themes.

.map(), and forEach() both are different from each other. The forEach() method iterates over a list and applies some operation with side effects to each list member (for example: saving every list item to the database) and does not return anything.

The map() function accepts a function as a parameter, then iterates over a list and transforms each element of the array then returns a new array and does not return anything.

const numbers = [5, 4, 3, 2, 1]
numbers.map(x => x * x)
// Output: [25, 16, 9, 4, 1]

In the above example, we are getting the square of each element of the array using the .map() method, so first we passed a function as a parameter `x` which will represent each element of the array. then multiply (x*x) with the same element it will apply to each element and return the square of the elements in the array. In the above example, the original array is the same. But returns a transformed array.

The ForEach() Method

forEach() method also accepts a callback function as a parameter, and iterates over the list of the element in the array, but instead of returning an array-like map() method it returns undefined

const people= [
  { id: 1, name: "john" },
  { id: 2, name: "robbert" },
  { id: 3, name: "jackson" },
]

people.forEach(el => console.log(el.name))
Output : john
//       robbert
//       jackson

In the above example we used the .forEach() method which is iterate over the list of people’s names the same as the map() method it receives a callback function as an argument and then iterates over the list, but not returning anything like map() method returns a new array of transformed elements.

Chain to Other Methods

Another difference between both methods is the map() works with method chaining while forEach() does not. The map() method is chainable it can execute the chain of methods like reduce(), sort(), and filter() after running the map() method. But the forEach method cannot do the same job because it returns undefined.

const numbers= [1, 2, 3, 4, 5]
numbers.forEach(x => x * x).reduce((total, value) => total + value)
//Error: Uncaught TypeError: Cannot read property 'reduce' of undefined
numbers.map(x => x * x).reduce((total, value) => total + value)
//Output: return value: 55

In the above example, we test both methods with a chain of other methods and you can see the output of both examples. forEach() method returns an error (can’t read the property of ‘reduce’ of undefined) while the map() method performs all operations and return the value.

Conclusion

Both methods .map() and .forEach() iterate on the array but the map() method returns a new transformed array while the forEach() method returns undefined. The map() method has the ability to chain other methods but forEach() method can’t be chained with other methods.