forEach vs map method in Javascript

  1. forEach method

The forEach() method executes a provided function once for each element in an array. After executing the function for every array element, this method changes the values of the existing array elements according to the result of the provided function. Hence forEach() is a mutator method. Also, forEach method doesn’t return anything (undefined).

  1. map method

The map() method, similar to the forEach() method, executes the provided function once for each element in an array. But unlike the forEach() method, it creates a new array with the results of calling a function for every array element. Hence map() method relies on immutability. Also, map() does not execute/call the function for those array elements without values.

Example:

const exampleArray = [1, 2, 3, 4, 5]

console.log(exampleArray.forEach(x => x * x * x));
//Output: (undefined)

console.log(exampleArray.map(x => x * x * x));
//Output: [1 , 8, 27, 64, 125 ]

For more information visit below link.
forEach vs map method in Javascript- Reference

1 Like