Difference between Array.Map() and Array.forEach().

Difference between Array.Map() and Array.forEach().

There are two most important array methods in javascript, Array. Prototype.Map() and Array. Prototype.forEach(), both of these methods are used to iterate over the array but there is a difference between these two methods which creates confusion, let's talk about them.

DEFINITIONS:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

example-

const array = [1,4,9,16]

const map1 = array.map(x => x *2);

console.log(map1);

OUTPUT:- [ 2, 8, 18, 32 ]

This means that the map method will produce a new array. It will always return the same number of items.

Whereas, the forEach() method executes a provided function once for each array element. example-

let friends = ['heena', 'rutkar','sanika'];

friends.forEach(function(e){
    console.log(e);
})

OUTPUT:- 'heena' 'rutkar' 'sanika'

One thing about the map is it returns undefined in the mapped array! let's see an example

let numbers = [1, 2, 3, 4]
let filteredNumbers = numbers.map(function(num, index) {
  if (index < 3) {
     return num
  }
})
// index goes from 0, so the filterNumbers are 1,2,3 and undefined.
// filteredNumbers is [1, 2, 3, undefined]
// numbers is still [1, 2, 3, 4]

##1. Return value: The first difference is the return value of both these methods. The return value of forEach() is undefined, whereas the map() method returns A new array with each element being the result of the callback function. Example:

const numbers = [1,3,5]

const newNumbers = numbers.forEach((e)=>{
    console.log(e);

})
console.log(newNumbers);

return value: undefined

const myArray = [1, 2, 3, 4, 5]
myArray.map(x => x * x)

return value: [1, 4, 9, 16, 25]

2.Chaining other methods:

The second difference is that we can chain different methods like reduce(), sort()...with the map() method, we cannot do the same with forEach() because of its return value undefined. Example:

const arr = [2,4,6,8];

const arr2 = arr.map((e)=> {
    return e*2

}).filter((e)=> {
    return e > 10;
})

console.log(arr2);

OUTPUT:[ 12, 16 ]

3.What to use Map() or forEach()?

If we don't want to use the new generated array further from the map() method, we can prefer to use the forEach() method instead.