Map method question

Tell us what’s happening:

const ratings = watchList.map(movie => ({
  title: movie['Title'],
  rating: movie['imdbRating']
}));

can anyone explain to me please, why I need the second group of parentheses thank you.

Challenge: Use the map Method to Extract Data from an Array

Link to the challenge:

Perhaps a different way to look at the same question, is to pull that inner parentheses out into a named function:

const getTitleAndRating = (movie)=>{
  // we want to return an object here, only containing
  //  the values we might want.
  return {title: movie['Title'], rating: movie['Rating']};
}

const ratings = watchList.map( getTitleAndRating );

So in the original, this bit:

movie => ({
  title: movie['Title'],
  rating: movie['Rating']
})

… is a one-liner “fat arrow function”. Given the input object, it’s immediately returning that output. But as the output is an object, we can’t simply return { title, rating}, as the arrow function would then look like this:

movie => { title: movie['Title'], rating: movie['Rating'] }

and the fat-arrow sees the { } and says “Oh hey, I have a function body. I’m not a one-liner any longer! Yay me! Let me just run the stuff in these { }… well, poot.”

It can’t run that, it isn’t a function body. It’s an object that we want to return. So we wrap it in ( ) so that javascript doesn’t see it as a function body, but as a returned object.

2 Likes