forEach vs map - Javascript Array methods

In this blog post, we are going to cover 2 very important and very much used Javascript array methods called forEach and map. Both the methods have similarities and differences. Let us start discussing it.

Syntax:

<ARRAY>.forEach(function(element, index) {
   // code
});

const <NEWARRAY> = <ARRAY>.map(function(element, index) {
   // code return statement
});

Features:

1. Mutability

The meaning of mutation is to update or change.

The callback function of forEach mutates the original array, whereas the callback function of the map method creates a new array, without mutating the original array as it is.

2. Return value

Continuing from the above point, the map method takes a return statement to create a new array. Whereas the return statment within a forEach will be “undefined”.

3. Ability to chain methods

Map method allows method chaining, the process of calling one method after another. The output of the previous method will be the input of the next method.

Method chaining is not possible in forEach callback funcation, as it returns “undefined”. This output cannot be passed as a valid array input to the next chained method.

4. Performance

Map method is considered to be faster than the forEach – As per the tests on jsperf.

5. Use case

forEach method can be used when you are working on the array, i.e you can change the original array.

map method can be used when you are working with the array, i.e you will create a new array, without disturbing the original array.

Leave a Comment

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