Image

JavaScript Difference Between forEach() & map().

You guys have worked lot with forEach() & map() method, as these two important array iterate method to access element of an array.

So we'll go over when to use which method, as well as their differences and relative importance.

First we will start with forEach() method..


Two important rule while using forEach() method


  1. forEach() iterate on each element in an array
  2. forEach() does not execute on empty array


Now if we talk about syntax


  1. array.forEach(function(currentValue, index, arr), thisValue)  

Lets check in detailed over each element of syntax

  1. function => A function required so that it can itrate over each element.
  2. currentValue => current value of array element
  3. index => current index of array element
  4. arr => An complete array of current element
Lets check output of each element of syntax that we have discussed.

Our array

  1. const usersArray = ["alex","martin","john","rita","nancy"];  

1.currentValue console output

  1. usersArray.forEach((currentValue,index,arr)=>{  
  2.   console.log(currentValue)  
  3. })  
Output
  1. "alex"  
  2. "martin"  
  3. "john"  
  4. "rita"  
  5. "nancy"  

2.index console output


  1. usersArray.forEach((currentValue,index,arr)=>{    
  2.   console.log(index)    
  3. })    
  4. //Output    
  5. 0    
  6. 1    
  7. 2    
  8. 3    
  9. 4    

3.arr console output


  1. usersArray.forEach((currentValue,index,arr)=>{  
  2.   console.log(arr)  
  3. })  
  4.   
  5. //Output  
  6. ["alex""martin""john""rita""nancy"]  
  7. ["alex""martin""john""rita""nancy"]  
  8. ["alex""martin""john""rita""nancy"]  
  9. ["alex""martin""john""rita""nancy"]  
  10. ["alex""martin""john""rita""nancy"]  


Now Lets discuss about map() method in detailed

Important rule while using map() method

  • map() iterate on each element in an array
  • map() does not execute on empty array
  • map() method does not change main array
  • map() method return new array of element.

Syntax

  1. array.map(function(currentValue, index, arr), thisValue)  
  1. const usersArray = [1,2,3,4];  
  2.   
  3. const returnArray = usersArray.map((currentValue,index,arr)=>{  
  4.   return (currentValue*2)  
  5. })  
  6. console.log(returnArray);  
  7. //Output  
  8. [2, 4, 6, 8]  

Categories: Java Script Tags: #JavaScript,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.