Look at the code below:
function sayHello(name){
const nameToPrint = name || "Unknown"
console.log('Hello' + nameToPrint)
}
sayHello('Tylor')
// Hello Tylor
sayHello()
//Hello Unknown
This function is a totally valid function. The value of nameToPrint
will either be a name passed in, or Unknown, in case the argument name
is not provided.
Now let's change this a little bit:
function sayHello({name}){
const nameToPrint = name || "Unknown"
console.log('Hello' + nameToPrint)
}
sayHello('Tylor')
// Hello Tylor
sayHello()
//Cannot destructure property 'name' of 'undefined' as it is undefined.
The function, now, will throw an error if the argument name
is not provided. This is due to the fact that it will try to destructor from an object which is not provided(AKA from undefined), which will ultimately result in an error. by adding ={}
we are adding a default value for the object. So now, if the argument(s) are not provided, they will be undefined(a falsy value); and, the values for those arguments, will be the fallback ones(the values after ||
).
Going back to our example:
function sayHello({name} = {}){
const nameToPrint = name || "Unknown"
console.log('Hello' + nameToPrint)
}
sayHello('Tylor')
// Hello Tylor
sayHello()
//It will try to extract the property name from object {}
// The value of name will be undefined, so the value of nameToPrint will be "Unknown"
//Hello Unknown
To conclude, trying to access a property of undefined, will trigger an error, but trying to access a property of an empty object, will only cause the value to be undefined.
See this for more info