Object Property Shorthand

Tell us what’s happening:
So, I’m running into some confusion. All in all, it is easy enough to pass the test, but it feels more like I’m just copying what I’m seeing in the explanation and not really learning (thats a problem that I notice in a lot of the sections thus far but w/e).

I notice that the function syntax here has parentheses surrounding the curly brackets and I have no idea why. Normally the code inside a function is bracketed by curly brackets but here it’s using the parentheses while I assume the returned object is being defined by the curly brackets? I’m just really unclear about this in general and it is frustrating when I am genuinely trying to learn but the explanations behind why things are the way they are is lacking.
Your code so far

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36.

Challenge: Write Concise Object Literal Declarations Using Object Property Shorthand

Link to the challenge:

If you take off the ()s, you’ll see an issue:

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

console.log(createPerson("bob", 99, "man"))

The source of this issue lies with arrow function syntax:

If an arrow function sees {}s, it expects to see a function body, and a function body has no return value unless you use the return keyword:

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

console.log(createPerson("bob", 99, "man"))

But this is really annoying to write all those extra characters. We like the implied return. Its short and programmers are lazy.

So JavaScript introduced special syntax to be able to return objects from arrow functions without the return keyword:

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

console.log(createPerson("bob", 99, "man"))
1 Like

Thanks for the quick reply! I think I understand – the parentheses are there primarily to have the arrow function syntax read the object as an object and not assume the curly brackets are a chunk of code for the function to then execute. I may have phrased that poorly, I’m still quite new to coding and working on getting my head around things.

1 Like

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