July 14, 2018
Difference Between Foreach and Map in Javascript
Foreach loop and map works pretty much the same. The only difference between these two is the return. In case of Foreach loop, you loop through all the items, modify them, but there is no return so you have store them in separate array inside the loop one by one. But in case of map, you loop through all items, modify them and it returns new array.
Examples are given below of Foreach and Map respectively:
var numbers = [1,2,3,4]; var even_numbers = []; numbers.forEach((number)=>{ even_numbers.push(number*2); }); console.log(even_numbers);
var numbers = [1,2,3,4]; var even_numbers = numbers.map((number)=>{ return number*2; }); console.log(even_numbers);