ES6 - Write Concise Object Literal Declarations Using Object Property Shorthand

hello i dont understand why there are brackets surrounding the {x,y} in

const getMousePosition = (x, y) => ({ x, y });

and our code uses return , and no similar brackets in

const createPerson = (name, age, gender) => {
  // Only change code below this line
   return{
    name,
    age,
    gender
  };
  // Only change code above this line
};

doesn’t the arrow function do away with the necessity of writing return ? and what are the brackets for ?

It can do away with needing an explicit return statement, but that doesn’t mean it can’t have an explicit return statement.

In fact, if the first character after the arrow is an opening curly brace then you are required to have a return statement. That is why the createPerson function above needs a return statement.

But if the first character after the arrow is not an opening curly brace then you have an implicit return and it will just return the value of the expression after the arrow without needing a return statement.

So what if you want to use an implicit return to return an object? An object is created with opening/closing curly braces, so it seems like you could do:

const returnObj = (x, y) => {x, y};

But remember what I said above, if the first character after the arrow is an opening curly brace then you are required to have a return statement, so this won’t work. But there is a “hack” to fix this, you can wrap the object in parentheses so that the first character after the arrow is a parens instead of a left curly:

const returnObj = (x, y) => ({x, y});

That’s why the parentheses are there, to allow you to return an object using an implicit return with an arrow function.

1 Like

Thank you very much this has been very helpful

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