Concise Declarations Using Object Shorthand

Hello,
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-object-property-shorthand

Why this solution which contains two “{ }” ?
Because in the exemple of lesson there is one “{ }” inside one “( )”.

Is it a second way to write this kind of concise declaration ?

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

When you use the return keyword, it must be inside a function body with curly braces ({}).

You can omit the containing braces and the return by using parentheses (()) instead.

Ok, and in this exercice I couldn’t do this without “return” because of the curly braces before and after the two line of comment, correct ?

Normally with a arrow function you can return by having no curly brackets:
() => //return value here

This of course limits what you can do with the function so alternatively you can provide curly brackets:

() => {
//do stuff in here
}

As you can see using the brackets there will be interpreted as a block of code like it would be with a regular JavaScript function, but if you want to return an object immediately you need to parentheses around the brackets so they will be interpreted as an object rather than a block of code:
() => ({})
That will return an empty object.

2 Likes

Perfect, thanks a lot caryaharper :wink:

1 Like

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