Use of map method VS forEach loop

So, I’ve recently learnt about the map method present in arrays.
Now my question is that why( or when ) shall I use map method instead of the forEach loop?

Both map and forEach giving the same result

var watchList = [
                 {  
                   "Title": "Inception",
                   "Year": "2010",
                   "Rated": "PG-13",
                   "Released": "16 Jul 2010",
                   "Runtime": "148 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Christopher Nolan",
                   "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
                   "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
                   "Language": "English, Japanese, French",
                   "Country": "USA, UK",
                   "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.8",
                   "imdbVotes": "1,446,708",
                   "imdbID": "tt1375666",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Title": "Interstellar",
                   "Year": "2014",
                   "Rated": "PG-13",
                   "Released": "07 Nov 2014",
                   "Runtime": "169 min",
                   "Genre": "Adventure, Drama, Sci-Fi",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan, Christopher Nolan",
                   "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
                   "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
                   "Language": "English",
                   "Country": "USA, UK",
                   "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.6",
                   "imdbVotes": "910,366",
                   "imdbID": "tt0816692",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "The Dark Knight",
                   "Year": "2008",
                   "Rated": "PG-13",
                   "Released": "18 Jul 2008",
                   "Runtime": "152 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
                   "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
                   "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
                   "Language": "English, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
                   "Metascore": "82",
                   "imdbRating": "9.0",
                   "imdbVotes": "1,652,832",
                   "imdbID": "tt0468569",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Title": "Batman Begins",
                   "Year": "2005",
                   "Rated": "PG-13",
                   "Released": "15 Jun 2005",
                   "Runtime": "140 min",
                   "Genre": "Action, Adventure",
                   "Director": "Christopher Nolan",
                   "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
                   "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
                   "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
                   "Language": "English, Urdu, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
                   "Metascore": "70",
                   "imdbRating": "8.3",
                   "imdbVotes": "972,584",
                   "imdbID": "tt0372784",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Avatar",
                   "Year": "2009",
                   "Rated": "PG-13",
                   "Released": "18 Dec 2009",
                   "Runtime": "162 min",
                   "Genre": "Action, Adventure, Fantasy",
                   "Director": "James Cameron",
                   "Writer": "James Cameron",
                   "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
                   "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
                   "Language": "English, Spanish",
                   "Country": "USA, UK",
                   "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
                   "Metascore": "83",
                   "imdbRating": "7.9",
                   "imdbVotes": "876,575",
                   "imdbID": "tt0499549",
                   "Type": "movie",
                   "Response": "True"
                }
];

var ratingByMap= [];
var ratingByForEachLoop= [];


// USING MAP METHOD
ratingByMap = watchList.map(el=>{
  return {
    title : el.Title,
    rating : el.imdbRating
  }
});
console.log(ratingByMap); 


// USING FOREACH LOOP
watchList.forEach(el=>{
  ratingByForEachLoop.push({
    title : el.Title,
    rating : el.imdbRating
  });
});
console.log(ratingByForEachLoop); 

Just tell me when and why should I choose map over foreach

—Thank you :smiley:

1 Like

Yes, they can both accomplish the same thing in different ways. Sometimes different tools can’t do the same thing sometimes they can.

For me, map is better when you are creating an array where each element is based on the element of the old array. That is what you are doing.

And forEach is better when you need to do something with each element of an array. For example, maybe you have an array of strings and you want to console.log them one at a time.

Yes, you could use forEach for this problem, but map is the more natural fit.

1 Like

I would think one of the reason one will be using map over forEach is to avoid mutation on the result array.

forEach is slower than map. forEach will alter the current array you iterate, map will return a new array.

forEach will mostly be used when you don’t want to alter the data in your array but want to do something with it, like logging it or saving to a database.

map will be used when you want to alter the data, since it returns a new array you can chain other methods like filter(), reduce() etc.
Example:
Changing the values of every item in an array with map and then filter out all values above a certain number. This can be done in one line like this:
arr.map(num => num * 5).filter(num => num > 10);
Note that it doesn’t change the original values of arr, but it returns a new array.

1 Like

Hi,

IMO map should be used when you are doing some transformation of the data - like in your example just extract some data from the original array and get a new array with the transformed data.

forEach when you are not trying to transform/change the data but would like to just execute a certain action.

Note: map doesn’t allow for the callback function to mutate the original array, whereas forEach callback function allows it. map is faster than forEach and returns new array, whereas forEach doesn’t return any value.

I hope this helps. : )

1 Like

If you need to just iterate over the element of the array or list and do some action on each element then you should use foreach method but if you want to perform an operation which create a new array then you should use map.

for example:

You should use foreach when you need to insert data into a database or something like this.

And you should use a map when you need the square of all the elements present in the array or something like this which alter the element of the array.

For more details, you can refer to this article https://codesquery.com/javascript-map-vs-foreach-methods/

1 Like

map, for every element in a list, literally maps each value of one type to a value of another type according to the function you give it.

So, given a list of type A and a function that maps type A to type B, it returns a list of type B.

// Input is a list of strings:
const input = ["1", "2", "3"];

// Mapping function converts a string to a number:
function stringToNumber (string) {
  return Number(string);
}

// Output is a list of numbers
const output = input.map(stringToNumber)

forEach, for every element in a list, performs some side effect, it doesn’t return anything.

const input = ["1", "2", "3"];

// Log values in the list:
function logValue (v) {
  console.log(v);
}

input.forEach(logValue);

// This is just `undefined`, there is no output
// const output = input.forEach(logValue)

Edit: forEach is just a general iterator: iterate over a list of things and do something elsewhere in the system. You can use it to get the same end result as map (create a new array, run forEach on the original array, in the callback do something and push the result to the new array, return the newArray), ie use it as a for loop, but that’s not really the point of it. A common usecase is this:

querySelectorAll('.someHtmlElement').forEach(element => /* do some DOM manipulation */);

So you find every element on a webpage with the class .someHtmlElement, then you use forEach to loop over them, and in the callback you do something for each one.

1 Like