ES6 - Use Destructuring Assignment to Pass an Object as a Function's Parameters

Tell us what’s happening:

Hi, in the description, there’s this example:

const profileUpdate = ({ name, age, nationality, location }) => {

}

As you can see, there are curly brackets after the arrow. When I use them in the exercise, it raises an error. It accepts my solution without these brackets, though.

Why? Is the tutorial example wrong?

Thanks in advance

Challenge Information:

ES6 - Use Destructuring Assignment to Pass an Object as a Function’s Parameters

When using arrow functions, you can have two different syntax forms:
returning an expression and using a code block

expression

const add = (num1, num2) => num1 + num2

code block

const add = (num1,  num2) => {
    // other code
    // other code ...
     return num1 + num2
}

The obove two are equivalent,The usage scenarios will be different.
Holp can help you!

2 Likes

Yes, essentially you can use curly brackets if you choose, but you would also need to use the return keyword in that case.

Arrow syntax allows for a more compact function expression, which is very useful if your function contains only a single expression.

1 Like

Thanks a lot, both of you! That explains it.

One more point, with the concise arrow function syntax if you need to return an object you have to wrap it in parentheses.

const member = {
  id: 1,
  name: "Gandalf",
  role: "Wizard",
};

const userRoleStatus = ({ id, name, role }) => ({
  id,
  name,
  role,
  roleStatus: role ? "Assigned role" : "No role assigned",
});

console.log(userRoleStatus(member)); // { id: 1, name: 'Gandalf', role: 'Wizard', roleStatus: 'Assigned role' }
1 Like

Cool. That’s a constructor, isn’t it?

Not really but I understand why you would call it that. You might call it a factory function. There are different names for functions that return objects and it depends on the use case.

I just wanted to show a function returning an object. Not sure I would call it anything, other than maybe a utility function.

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