JavaScript map vs. forEach: Which one to use
2 min readApr 16, 2022
In JavaScript, forEach and map are two of the most popular methods to work with arrays. Both the methods are helps to iterate through the array
The forEach Method:
- This method helps to loop through an array
- foreach will return undefined, hence this method is not chainable.
- Do not use this method if you want to change anything in the existing array
let numbers = [1, 2, 3, 4, 5];//output the square of each numberlet returnValue = numbers.forEach((num) =>console.log(`${num} x ${num} = ${num * num}`));console.log(numbers); // returns [1, 2, 3, 4, 5] the array hasn't changedconsole.log(returnValue); // returns undefined
The map Method:
- This method will iterate an array and returns new array, hence we can chain other array methods
let numberArray = [1, 2, 3, 4, 5];let returnValue = numberArray.map((num) => num * num);console.log(numberArray); // returns [1, 2, 3, 4, 5]console.log(returnValue); // returns [1, 4, 9, 16, 25]
As we can see the existing array values are not changed while using map method
map method will be helpful to chain the other array methods,
let numberArray = [1, 2, 3, 4, 5];//output the square of each number and sum itlet returnValue = numberArray.map((num) => num * num).reduce((acc, curr) => acc+ curr);console.log(numberArray); // returns [1, 2, 3, 4, 5]console.log(returnValue); //returns 55
As we can see in the above code map method chained with reduce method and returns a value as 55 (1+4+9+16+25)