Differences Between forEach() and map()

Every Javascript developer should know the difference between forEach() and map().
The points to be noted:
When to use either forEach() and map()
Performance speed
The ability of chaining process
Syntax:
forEach():
forEach((currentElement, indexOfElement, array) => { ... } )
map():
map((currentElement, indexOfElement, array) => { ... } )
Parameters:
currentElement: This is the current element that is being processed in the callback.
indexOfElement: The index of that current element inside the array.
array: The array on which the whole operation is being performed.
Question 1:
Return values:
/* forEach method */
let nums= [1, 2, 3, 4];
nums.forEach((element, index) => {
nums[index] = element * element;
})
console.log(nums);
/* map method */
let nums= [1, 2, 3, 4];
nums.map((element, index) => {
nums[index] = element * element;
})
console.log(nums);
when we run both codes the output will be same.
[1, 4, 9, 16]
[1, 4, 9, 16]
But when we try to return the values
/* forEach method */
let nums= [1, 2, 3, 4];
nums.forEach((element, index) => {
return element * element;
})
/* map method */
let nums= [1, 2, 3, 4];
nums.map((element, index) => {
return element * element;
})
O/p varies now:
undefined
[1, 4, 9, 16]
forEach() returns undefined.
So, when we try to return values using forEach it returns undefined because it won't create a new and dummy list like map. It tries to use the same array. Behalf, the map creates a new array and modifies it. so, it won't throw any error.
Question 2.
Chaining methods
When the output gets undefined, the chaining like reverse(), reduce(), filter() etc.. may through an error, Because the o/p is undefined, and throw a type error.
/* forEach method */
let nums= [1, 2, 3, 4];
nums.forEach((element, index) => {
return element * element;
}).reverse()
/* map method */
let nums= [1, 2, 3, 4];
nums.map((element, index) => {
return element * element;
}).reverse()
O/p varies now:
[16, 9, 4, 1]
Final Thoughts
As always, the choice between map() and forEach() will depend on your use case. If you plan to change, alternate, or use the data, you should pick map(), because it returns a new array with the transformed data.
But, if you won't need the returned array, don't use map() - instead use forEach() or even a for loop.
| forEach() | map() | |
| 1 | The forEach() method does not return a new array based on the given array. | The map() method returns an entirely new array. |
| 2 | The forEach() method returns “undefined“. | The map() method returns the newly created array according to the provided callback function. |
| 3 | The forEach() method doesn’t return anything hence the method chaining technique cannot be applied here. | With the map() method, we can chain other methods like, reduce(),sort() etc. |
| 4. | It is not executed for empty elements. | It does not change the original array. |
Share your thoughts!!!!!



