ES6 Array Methods forEach() and map()

carter halfmann
Aug 31, 2018 · 2 min read

ES6 array methods forEach() and map() are two JavaScript methods that are used to iterate through arrays. The forEach() method has some code inside of it and then executes this said code once for every element present in the array that it has been assigned to. The forEach() method cannot be terminated early, meaning this method will keep iterating through the array until it has reached the end. If the code provided within the method involves removing elements from the array, like shift() or pop(), then the method will keep iterating until it has reached the end of the existing list. Map() is similar to forEach(), except it actually returns a second value for each value in the array, and creates a new array with the new values inside it. It also has a different syntax than forEach(). These 2 methods are very similar, but what are the differences? The forEach() method can actually mutate the array it is assigned to. The map() method does not mutate the array, but instead creates a new array. This is the main difference between the two methods. Here are some syntax examples:

arr=[1, 2, 3, 5, 8]
arr.forEach(num){
num=num*2;
return num;
};
//should return [2, 4, 6, 10, 16]
var dos= arr.map(num){
return num * 2;
};
//should return [2, 4, 6, 10, 16]

As you can see, these two methods are pretty different, but can accomplish similar tasks. Each has different uses and will be appropriate in different scenarios. It will be a challenge to learn which situations each will be most useful for.

ForEach() loop in action
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade