Why are there brackets in the map function after the arrow function

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

You use brackets to contain expressions in JS, exactly same as you do in maths (ie evaluate the expression in brackets as one thing). In this case, you want to return an object.

Curly brackets are used to denote a block of code (in this case the body of a function) as well as being the syntax for objects. There are two possible things they can mean.

If you leave them off, what you’ve written is the same as:

function (item) {
  title: item[“Title”],
  rating: item[“imdbRating”]
}

JS has to assume you meant the curly brackets to mean “this is a function body” rather than “this is an object”, because it’s a function, and you have to use curly brackets if the function body has more than one expression (eg the code in it spans multiple lines, does a few things).

Whereas if you tell JS the object needs to be evaluated, what you’ve written is the same as:

function (item) {
  return ({
    title: item[“Title”],
    rating: item[“imdbRating”]
  });
}

Which is correct, same thing as

function (item) {
  return {
    title: item[“Title”],
    rating: item[“imdbRating”]
  };
}
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.