Array.map vs Array.forEach


If you are working with JavaScript, then you must have come across these two similar looking array methods: Array.prototype.map() and Array.prototype.forEach().

Most of the developers thinks that Array.map function and forEach for an Array is the same, but it is not. Lets see some examples:
1. Array.prototype.forEach
forEach can be used just like a traditional ‘for loop’ that iterates each of the array element once.

let arrayElements = ['A','C','D'];  
arrayElements.forEach((ele)=>{  
  console.log(ele);  
 })  

The above example will generate the following –
A
C
D

2. Array.prototype.map
The map() function creates a new Array with the results of calling a function for every element of the calling array.

let arrayElements = [1, 4, 6];  
var result = arrayElements .map((ele)=>{  
  return (ele * 2);  
});  
console.log(result);  

The output of the code is:
[ 2, 8, 12 ]
In the above example we are iterating through each element of Array and multiplying it by 2.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.