forEach and map method both use to iterate over arrays , but they serve different purposes and have distinct behaviors.
1.forEach method
The forEach method is used for iterating through each element of an array. It doesn’t create a new array; instead, it directly modifies the elements of the existing array.
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number * 2);
});
// Output:
// 2
// 4
// 6
// 8
// 10
forEach used when your purpose is to iterate over each element of array without needing to create new array.
2. map method
map method on other hand also used for iterating through each element of an array but it can return new modified array without changing the original array
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(number) {
return number * 2;
});
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
map method used when your purpose is to return new modified array
In summary:
Use forEach when you want to iterate through an array and perform side effects or actions on each element without creating a new array.
Use map when you want to iterate through an array, transform its elements using a function, and create a new array with the transformed values.
Note:- Remember that both methods iterate over each element in the array, so the provided function will be executed for each element. The main difference lies in the purpose and outcome of using each method.
Top comments (0)