Friday, September 27, 2024
Google search engine
HomeLanguagesJavascriptDifference between forEach() and map() loop in JavaScript

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

When we work with an array, it is an essential step to iterate on the array to access elements and perform 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.

JavaScript .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 produce 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 below, we can deduce the working of both methods.

[1, 4, 9, 16]
[1, 4, 9, 16]

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:

undefined

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:

[1, 4, 9, 16]

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).

[16, 9, 4, 1]

Differences between forEach() and map() methods:

  forEach() map() 
1 The forEach() method does not returns a  new array based on the given array. The map() method returns an entirely new array.
2 The forEach() method returns “undefined“. The map() method returns the newly created array according to the provided callback function.
3 The forEach() method doesn’t return anything hence the method chaining technique cannot be applied here.  With the map() method, we can chain other methods like, reduce(),sort() etc.
4. It is not executed for empty elements. It does not change the original array.

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.

RELATED ARTICLES

Most Popular

Recent Comments