ES6 - Write Concise Object Literal Declarations Using Object Property Shorthand

Tell us what’s happening:
I have the code passing… I just want to better understand what is going on with this syntactic sugar (Anyone else hate that phrase besides me?).

So, are we to assume the parameters are ALREADY OBJECTS or are they just values that get turned into keys for objects by name and their VALUE IS ASSIGNED to the value of the objects that are created by this function? It’s not clear… it’s just showing a possible representation without explaining what that representation actually is.

  **Your code so far**
const createPerson = (name, age, gender) => {
// Only change code below this line
return ({name, age, gender});
// Only change code above this line
  **Your browser information:**

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

Challenge: ES6 - Write Concise Object Literal Declarations Using Object Property Shorthand

Link to the challenge:

That ES6 syntactic form is a shorthand for:

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

Because the returned object has its properties with the same name as the arguments of createPerson function, with ES6 you don’t have to type more than what is shown above. It is an abbreviated way to do the same thing.

So, it’s assigning values to the values based off of what the parameters name, age, and gender already had passed in, correct?

Isn’t this bad practice? I mean using the name of the key as the name of the value seems to me lazy and confusing. I don’t think that using the same name in multiple places is ever a good idea and can be easily avoided… but since I am not in the realm of programmers just yet, I am guessing this is common practice?

That challenge is just an exercise to see that it is possible to be more concise.
The function createPerson, in fact, creates a ‘Person’, which is an object with the same property names as the arguments, and that way the properties being assigned with the arguments values.
If that function needed auxiliary calculations and more complex code, yes, you should give different names to distinguish the arguments from the returned object properties. Again, this is just an example of what you can do. Since the values you input into the function are not changed, you can do this as a ‘shortcut’.

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