DEV Community

Cover image for How to set default object parameter in Javascript
Sajidur Rahman Shajib
Sajidur Rahman Shajib

Posted on

How to set default object parameter in Javascript

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

  1. 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.

  2. 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 (1)

Collapse
 
__7df77be9ce1ff profile image
Эрих Гайлис

Thanks