The difference between forEach() and map()

The two most commonly used methods for iteration are Array.prototype.map() and Array.prototype.forEach(). It is necessary to understand their differences.

Both the forEach() and map() methods receive a function as a parameter. It then applies the parameters to each element.

The first difference is the return value.

The forEach() method returns undefined, while map() returns a new array containing the converted elements, but the return value is different.

const arr= [1, 2, 3, 4, 5]
arr.forEach(x => x * x)
//  undefined

arr.map(x => x * x)
//  [1, 4, 9, 16, 25]

The second difference is that map() can be followed by other methods.

You can append reduce(), sort(), filter(), etc. after executing map() method on an array, but forEach() cannot because it returns undefined.

The third difference is that map() does not mutate the array on which it is called.

The map() method returns a brand new array containing the converted elements and the same amount of data, without changing the original array. And forEach(), even if it returns undefined, it will change the original array with the passed callback function (callback).

Guess you like

Origin blog.csdn.net/qq_44721831/article/details/129266869
Recommended