What is the difference between the array methods map() and forEach()?
Both methods iterate through the elements of an array. map() maps each element to a new element by invoking the callback function on each element and returning a new array.
On the other hand, forEach() invokes the callback function for each element but does not return a new array. forEach() is generally used when causing a side effect on each iteration, whereas map() is a common functional programming technique.
let arr = [1, 2, 3, 4, 5]arr.forEach((num, index) => {
return (arr[index] = num * 2)
})// arr = [2, 4, 6, 8, 10]let doubled = arr.map((num) => {
return num * 2
})// doubled = [2, 4, 6, 8, 10]
// arr = [1, 2, 3, 4, 5] => arr is unchangedIf you want to follow functional programming paradigm, map() is a better choice because forEach() will mutate the array elements directly, while map() will create a new array and keep the original array unchange.