Search code examples
javascriptobjectecmascript-6default-value

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


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?


Solution

  • 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).