Map and ForEach Difference Javascript
What is the difference between map & forEach?
Array Methods Javascript
- Both of these are array methods are used to iterate over the elements of the array
| Map Javascript |
forEach |
| Returns a new Array |
Doesn't return the new array, just iterates |
We can chain methods on map, arr.map().filter() |
We cannot chain methods on forEach |
| Use Case: To create a new Array |
Use Case: To iterate on the element like a basic for loop |
const arr = [2, 5, 3, 4, 7]
const mapResult = arr.map((element) => {
return element + 2;
})
console.log(mapResult); // [4, 7, 5, 6, 9]
// forEach doesn't return anything
const forEachResult = arr.forEach((element) => {
return element + 2;
})
console.log(forEachResult); // undefined
// Modifying original array using forEach
arr.forEach((element, index) => {
arr[index] = element + 2;
})