Map is working but forEach is not! Why?


#1

Hey,

Can some one please explain to me why this works:

let fruits = ['apple', 'orange', 'lemon'];
 
let output = fruits.map(function(item){
    return item;
});

console.log(output);

But the same code with forEach doesn’t work?

let fruits = ['apple', 'orange', 'lemon'];

let output = fruits.forEach(function(item){
    return item;
});

console.log(output);

Isn’t it that myNames is an array and forEach is a built-in method of Array?
Why is that the forEach is not working?

Thanks


#2

That’s the way forEach works. It only loops through arrays, it doesn’t also make a new array like map does.

forEach would be used if you wanted to do some work during the loop, like call a function, and nothing else. map is used for transforming data in an array to a new set of different data.

let fruits = ['apple', 'orange', 'lemon'];

let output = fruits.forEach(function(item){
    console.log(item);
    // return is ignored in forEach
});