Hello Devs,
Do you find any error when you set the default object as parameter? Let's talk about it.
const fullName = ({fname, lname})=> {
console.log(fname + ' ' + lname)
}
fullName({fname:'Sajidur', lname:'Rahman')
//your@console:~$ Sajidur Rahman
I Guess you already know what's going on in this simple function. In this topic this is our demo function.
const fullName = ({fname='Jhon', lname='Doe'})=> {
console.log(fname + ' ' + lname)
}
fullName({fname='Sajidur'})
//your@console:~$ Sajidur Doe
This parameter is an object where we set 2 properties with default value. If we don't pass any of the property, then default property will use. We pass only fname
that's why default lname
use.
const fullName = ({fname='Jhon', lname='Doe'})=> {
console.log(fname + ' ' + lname)
}
fullName()
//your@console:~$ TypeError: Cannot read property 'fname' of undefined
If we don't pass any parameter, then we will find this error. But why? We set default parameter right?
No, we didn't. We just set the default property value of an object. That object is our actual parameter.
const fullName = ({fname='Jhon', lname='Doe'} = {})=> {
console.log(fname + ' ' + lname)
}
fullName()
//your@console:~$ Jhon Doe
Now set a default parameter as an empty object {fname='Jhon', lname='Doe'} = {}
. Now it works, but why? Let's talk about it step by step.
This whole object
{fname='Jhon', lname='Doe'}
is a single parameter. For this parameter default parameter value is{}
. When the parameter is undefined that time this{}
empty object will appear.Now we have empty object. But we already set some default properties with value for empty object right?
fname='Jhon', lname='Doe'
Those properties now appear here with their default value.
So Dev, I hope you understand and find the solution if you stuck on this issue.
Top comments (0)