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

[Origin]: https://forum.freecodecamp.org/t/why-does-map-method-arrow-function-needs-to-return-obj-in-parentheses/355277

janpietrzyk Mar ’20

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]

DanCouper Mar ’20

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 };
};

Leave a comment