Why does map Method+arrow function needs to return obj in parentheses?

In Functional Programming exercise 7, we are tasked with using of the map method. While I was able to understand map method, there is something that confuses me about how arrow function returns object. Why are parentheses required when returning value using arrow function here?

For example:
const ratings = watchList.map(elem => ({mapMethodTitle: elem.Title}));

will return
[{"mapMethodTitle":"Inception"},{"mapMethodTitle":"Interstellar"},{"mapMethodTitle":"The Dark Knight"},{"mapMethodTitle":"Batman Begins"},{"mapMethodTitle":"Avatar"}]

However if we omit parenthesis like
const ratings = watchList.map(elem => {mapMethodTitle: elem.Title});
it will result in
[null,null,null,null,null]

In normal functions we can just return obj on its own:

let funcMetascore = function(elem) {
    return {funcMetascore: elem.Metascore,ID: elem.imdbID};
}

{ funcMetascore: '82', ID: 'tt0468569' }

{} is used to wrap a block of code. {} is also the syntax for an object literal.

someLabel: someThing is valid (if obscure) JS. someLabel: someThing is also how you define keys: values in an object literal.

, is an operator in JS. It is also used to seperate key:value pairs in an object literal.

Bearing that in mind, how does the JS interpreter know what this is, given it can be two completely different things:

const example = () => { foo: 1, bar: 2 };

That gets interpreted as

const example = () => {
  return foo: 1, bar: 2;
};

() would say “evaluate what’s inside the parentheses before doing anything else”, so

const example = () => ({ foo: 1, bar: 2 });

Gets interpreted as

const example = () => {
  return { foo: 1, bar: 2 };
};
2 Likes

arrow functions work in two ways, implicit return, of explicit return

with explicit return you have as usual the curly brackets around the body of the function

(...parameters) => {
   // do stuff 
   return result;
}

implicit return can be used when the function is of only one line:

x => x+2

but you can’t return an object in the same way as it will recognise the curly braces as those of the body of the function, and it will not work (it returns null because the function doesn’t run)
to make this work, you need to wrap the object in round parenthesis, so that the curly braces are not recognised as those of the function body

x => ({ y: x.a, b: x.c +2})
1 Like

Thank you both. You explanations made it very clear.
It sounds so obvious now, but somehow I missed it :slight_smile:

:slightly_smiling_face: it trips everyone up, it’s only obvious in hindsight

1 Like