DEV Community 👩‍💻👨‍💻

Ashik Patel
Ashik Patel

Posted on

forEach VS Map.

Let's keep it on point. JS has few methods for the Array to find or search or iterate items through particular Array. Here we want to discuss 2 mostly and widely used methods,

  1. forEach
  2. Map

Basic definition and example

forEach method can be used to iterate through an Array. This method will be provided with a callback function, which will be called for each and every item available in Array. An Important point to remember is that, forEach does not return an array, in fact it returns 'undefined'. So if you my man working on some logging or processing which does require every item of an array and does not required anything in return you should consider this method as your to-go tool. let's take an example.

Image description

let's now see what's that returnedValue is holding. any guess ?

Image description

Now, map method works same as the forEach but the major difference is that it returns the same length of the newly created array as on array it is being called. Means it does not return 'undefined' as forEach do, but it returns modified array according to the callback function of the same length. In addition to that, the callback is invoked for every items available in an element. You can always use this method when you want to do some processing or modification on every item of an array and use that newly created array further. example is given below.

Image description

Chaining ability.

wait wait wait, what the heck is that? well, in simple terms as you are now absolutely clear that forEach does not return anything and returning just 'undefined', it is not able to perform chaining operations like reduce, sort and etc. But but but, map is returning an array based on the callback modifications, we can chain methods on it. See it is that simple

When to use what ?

I will say you will encounter an 'Anti-Pattern' if using map and getting array in return, and for serveral reason you stupid dev does not want to use it further. So if you really do not need to use returned value please please go for forEach.
vice versa is also fine.

Performance ?

Well, depends on the several factors I do not want to dig into it.

Top comments (0)

Rust language vs others

Stop by this week's meme thread!