Why is the following function doing `greet({ name = 'Rauno' } = {})` instead of `greet(name = 'Rauno')`?

Viewed 92
function greet({ name = 'Rauno' } = {}) {
  console.log(`Hi ${name}!`);
}
 
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!

Although, I understand the basic functionality here... I don't understand what the need was to do greet({ name = 'Rauno' } = {}) instead of greet(name = 'Rauno'). Don't they achieve the same result? So, why?

2 Answers

the short answer is no.
assume you have your function and call it like below:

function greet({ name = 'Rauno' }) {
  console.log(`Hi ${name}!`);
}

greet(); // throws reference error

you are passing nothing(implicitly undefined) as the first argument. so javascript fails when it tries to access undefined.name and throws reference error. because undefined is not an object and has not a name property. so you should set a default value for the argument to cover undefined cases. then javascript tries to retrieve {}.name, it's undefined and the default value for name is retrieved(Rauno in your case).

In the given codeblock, the greet function accepts an object with a property of "name". See how the call looks: greet({ name: 'Larry' }) // Hi Larry!

If you wrote function greet(name = "Rauno") { /***/ } that function would accept a single string parameter, so you would call that like greet("@Grateful");

Related