-2

What is the particularity (specificity) of map() vs forEach in JavaScript ?

They work fine identically !

 <script type="text/javascript"> "use strict";
   const array1 = [12, 3, 7];
   const array2 = [];

   const dispEls=(el, idx, array1) =>
       array2.push("exp (a[" + idx+ "] = "+el+") = "+
       Math.exp(el).toFixed(2));

   array2.push("===== FOREACH");
   array1.forEach(dispEls);
   array2.push("===== MAP");
   array1.map(dispEls);

   console.dir(array2)
 /*[…]
 0: "===== FOREACH"
 1: "exp (a[0] = 12) = 162754.79"
 2: "exp (a[1] = 3) = 20.09"
 3: "exp (a[2] = 7) = 1096.63"
 4: "===== MAP"
 5: "exp (a[0] = 12) = 162754.79"
 6: "exp (a[1] = 3) = 20.09"
 7: "exp (a[2] = 7) = 1096.63"
 length: 8      */
 </script>

1 Answers1

3

map returns an array with the values returned from the function, while forEach does not. If you do not need the new array, prefer forEach.

Example using your code:

const array1 = [12, 3, 7];
const array2 = [];

const dispEls = (el, idx, array1) =>
  array2.push("exp (a[" + idx + "] = " + el + ") = " +
    Math.exp(el).toFixed(2));

array2.push("===== FOREACH");
let result_forEach = array1.forEach(dispEls);
array2.push("===== MAP");
let result_map = array1.map(dispEls);


console.dir(result_forEach)
console.dir(result_map)

The returned array of map is the values returned from push(the index, the element was pushed to)

mdatsev
  • 3,054
  • 13
  • 28