forEach vs map method javascript

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
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Privacy, cookie & data policy.