If you are working with JavaScript, then you must have come across these two similar looking array methods: Array.prototype.map() and Array.prototype.forEach().
Most of the developers thinks that Array.map function and forEach for an Array is the same, but it is not. Lets see some examples:
1. Array.prototype.forEach
forEach can be used just like a traditional ‘for loop’ that iterates each of the array element once.
let arrayElements = ['A','C','D']; arrayElements.forEach((ele)=>{ console.log(ele); })
The above example will generate the following –
A
C
D
2. Array.prototype.map
The map() function creates a new Array with the results of calling a function for every element of the calling array.
let arrayElements = [1, 4, 6];
var result = arrayElements .map((ele)=>{
return (ele * 2);
});
console.log(result);
The output of the code is:
[ 2, 8, 12 ]
In the above example we are iterating through each element of Array and multiplying it by 2.