map() vs forEach() in JavaScript

map() vs forEach() in JavaScript

map() Method:

The map() method is used for creating a new array from the existing one by applying a function to each one of the elements of the first
array.

forEach() method:

The forEach() method receives a function as an argument and executes it once for each array element. Same like map() method.

The returning value:

The first difference between map() and forEach() is the returning value.

The map returns a new array with the transformed elements whereas forEach method returns undefined.

Ability to chain:

The second difference between these array methods is the fact that map() is chainable. This means that we can attach reduce(), sort(), filter() and so on after performing a map() method on an array.

That’s something we can’t do with forEach() because it returns undefined.

When to use what:

  • The choice between map() and forEach() will completely depend on the use case.
  • If we need to change, alternate, or use the data, we should pick a map(), because as we know that it returns a new array with the transformed data.
  • But, suppose we don’t need the returned array, so we can skip the map() and will use forEach() or even a for loop.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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