Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Difference between forEach() and map() loop in JavaScript

  • Last Updated : 31 Aug, 2021

When we work with an array, it is an essential step to iterate on the array to access elements and performing some kind of functionality on those elements to accomplish any task.
For example, If you have an array of marks obtained by 20 students and you want to calculate their GPA, if you have an array of images and you want to render it on the frontend, etc. To manage such cases, you must have proper knowledge of how to access the element of the array and how to operate on them. 

Other than the basic language constructs i.e. for loop, while loop, and do-while loop, there are two widely used methods for iteration.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

.forEach() and .map(): These are the methods that are used to iterate on an array, more technically they invoke the provided callback function for every element of an array.

Syntax:



forEach((currentElement, indexOfElement, array) => { ... } )
map((currentElement, indexOfElement, array) => { ... } )

 

Parameters:

  • currentElement: This is the current element that is being processed in the callback.
  • indexOfElement: The index of that current element inside the array.
  • array: The array on which the whole operation is being performed.

Example 1: Our objective is to create such a type of functionality that can give square values of the elements of a given array. We have created two arrays, one is working with the forEach() and the other with the map(), and both producing the same result. The element and index are being accessed inside the callback function and we are assigning the square of each element at that index.

JavaScript




<script>
    /* forEach method */
    let myArray1 = [1, 2, 3, 4];
    myArray1.forEach((element, index) => {
        myArray1[index] = element * element;
    })
    console.log(myArray1);
  
    /* map method */
    let myArray2 = [1, 2, 3, 4];
    myArray2.map((element, index) => {
        myArray2[index] = element * element;
    })
    console.log(myArray2);
</script>

Output: With the output image below, we can deduce the working of both methods.

Example 2: We are performing the same functionality but the returned value of forEach() is “undefined” and the returned value of the map() method is an array. 

JavaScript






<script>
    let myArray = [1, 2, 3, 4];
  
    const returnValue = myArray.forEach((element) => {
        return element * element;
    });
    console.log(returnValue);
</script>

Output:

Example 3: The following example demonstrates the map() method.

JavaScript




<script>
    let myArray = [1, 2, 3, 4];
  
    const returnValue = myArray.map((element) => {
        return element * element;
    })
    console.log(returnValue);
</script>

Output:

Example 4: In this example, we are going to apply the chaining technique, the return value is being operated on the next instance method. We have used the array reverse() method for simplicity but it can be anything i.e sort, find, reduce, filter, etc. Even custom methods can be used for chaining.  

JavaScript




<script>
    let myArray = [1, 2, 3, 4];
  
    const returnValue = myArray.forEach((element) => {
        return element * element;
    }).reverse();
    console.log(returnValue);
</script>

Output:  The forEach() method is returning “undefined” and the next instance method(reverse) can be invoked by an array.  TypeError is being thrown by JavaScript.  

Example 5: The following code demonstrates the reverse() method for the result obtained from the map() method as implemented in the above code.

JavaScript




<script>
    let myArray = [1, 2, 3, 4];
  
    const returnValue = myArray.map((element) => {
        return element * element;
    }).reverse();
    console.log(returnValue);
</script>

Output: Here the map method returns an array that invokes the next instance method and which later provides the final returnValue(reverse of the invoking array).

Differences between forEach() and map() methods:

 forEach()map() 
1The forEach() method does not create a new array based on the given array.The map() method creates an entirely new array.
2The forEach() method returns “undefined“.The map() method returns the newly created array according to the provided callback function.
3The forEach() method doesn’t return anything hence the method chaining technique cannot be applied here. With the map() method, we can chain the other array Instance methods i.e returned value of the map() method invokes the next method in the chain.

Conclusion: As they are working with very few differences, also the execution speed is not significant to consider so it is time to think about, which one to choose? If you want the benefits of the return value or somehow you don’t want to change the original array then proceed with the map() otherwise if you are just interested to iterate or perform the non-transformation process on the array, forEach() could be the better choice.




My Personal Notes arrow_drop_up
Recommended Articles
Page :