Tell us what’s happening:
Hi! I just did " Use the map Method to Extract Data from an Array" challenge and I’m confused about arrow function syntax.
I wrote
let rating = watchList.map((obj) => {title: obj["Title"], rating: obj["imdbRating"]});
but could not pass this challenge until I added parentheses to the “body” of the array function:
let rating = watchList.map((obj) => ({title: obj["Title"], rating: obj["imdbRating"]}));
So, the question is, why do I need parentheses here? And in what situation should I use parentheses with ‘body’ of arrow function?
Thank you in advance!
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.
That’s correct, you need parentheses if you want to return object. The thing is JS parser when sees { after arrow assumes it’s a start of function block, rather then object as they both use same syntax:
{
//stuff here
}
By using parentheses you say “make me object first” and then return it
It seams to work with variables names only (incl. undefined), so there is no way you can do this 2:2 or this 'string':2, but somehow you’re allowed to do this: a:2.
The first example didn’t work because you weren’t returning an object, you were setting parameters with " : " inside a function’s code block, which expectedly gave you an error. In the second example, you sort of “cheated the system” and wrapped entire return statement into one thing to be executed.
Also, in the first example you didn’t have a single line function (when you added a comma it “moved” to another line) so the { } were treated as a start of a function code block, not an object wrapper to be returned with everything it contains.
Interesting. I wonder if this label behavior is composed into the way objects are built. labels behave almost exactly like object keys, but without the rest of the Object class behavior.
Bracket vs paranthesis is a simple difference of the word “return” .
Paranthesis implies that u are “returning” somethimg, where as brackets dont.
For ex
function rating(array){
return { title: obj["Title"], rating:obj["imdRating"]}
}
Without the return statement u are simply assigning an object to a function. Everytime you invoke the function, for example, rating([someArray]) you would be simply assigning an object to the function over and over again.