I don't understand the use of parenthesis here

Tell us what’s happening:

I understand what the code does, but I don’t entirely get how it’s written. I’ll try to explain.
First of all, I passed the challenge referencing the example (the function getMousePosition), which looks slightly different from the solution given. What I don’t understand is the use of the parenthesis both in the example and in my solution: shouldn’t an arrow function use braces after the arrow? If I’m not wrong it’s the first time I see it written this way.
Does the parenthesis substitute the return keyword? The solution given uses braces and the return keyword.

Your code so far


const createPerson = (name, age, gender) => ({
  name,
  age,
  gender
});


console.log(createPerson('marco', 34, 'm'));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:78.0) Gecko/20100101 Firefox/78.0.

Challenge: Write Concise Object Literal Declarations Using Object Property Shorthand

Link to the challenge:

You’re right, in part. If you were to have a multi-line fat arrow function, you’d have curly braces.

But in this case, we’re returning something with a single line - returning an object. Remember, the curly braces surround the object literal. So if we have a one-line fat arrow function that returns an object literal, we need a way to tell javascript “return this as an object, don’t run it as a function body.”

So wrapping the literal in parentheses causes the literal to be created, as an evaluation, and then the arrow function simply returns the contents of the parentheses… Your object itself.

1 Like

Thank you, now it’s clearer. I was confused because the lessons about arrow functions didn’t mention that. I’ve also found something in the Mozilla docs about JavaScript.

1 Like

it’s a funky look, but it makes sense when you get into it.

Also, for reference, another great one-stop doc-resource (built and maintained by FCC!) is devdocs - https://devdocs.io

1 Like

This is a gem, thank you!

1 Like