Difference between forEach() and map():
example:
const numbers = [45,10,25,30,60];
function display (value, index, array ){
return value * 2;
}
const forEachReturn = numbers.forEach(display);
const MapReturn = numbers.map(display);
console.log(forEachReturn);
console.log(MapReturn)
console.log(numbers);
output:
undefined
[ 90, 20, 50, 60, 120 ]
[ 45, 10, 25, 30, 60 ]
example:
const numbers2 = [1, 2, 3];
const resultForEach = numbers2.forEach(num => num * 2);
console.log(resultForEach);
const resultMap = numbers2.map(num => num * 2);
console.log(resultMap);
output:
undefined
[ 2, 4, 6 ]
example:
const users = [
{ id: 1, name: "Sam" },
{ id: 2, name: "Alex" }
];
const usernames = users.map(user => user.name);
console.log(usernames);
const username = users.forEach(user => user.name);
console.log(username)
output:
Array [ "Sam", "Alex" ]
undefined
example:
(TBD)
const sparseArr = [1, , 3, , 5];
sparseArr.forEach(n => console.log(n));
const mapped = sparseArr.map(n => n * 2);
console.log(mapped);
output:
1
3
5
[ 2, <1 empty slot>, 6, <1 empty slot>, 10 ]

Top comments (0)