Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does passing arguments in this way mean?

I'm learning about javascript and I see this block of code that I don't understand:

exports.configure = ({
   expressapp = null,
   userdb = null,
   path = '/myroute'
} = {}) => { 
   // handle routes
};

I'm most confused about the structure of the argument being passed in and what is going on inside there. Where can I find more information about that so I can read about it? What is it even called when you pass arguments like that? Why would you want to do it this way?

like image 565
cocoPuffs Avatar asked Oct 15 '25 11:10

cocoPuffs


1 Answers

The pattern is a destructuring assignment which assigns a plain object as the default parameter, to avoid TypeError if no value is passed to the function.

const exports = {};

exports.configure = ({
   expressapp = null,
   userdb = null,
   path = '/myroute'
}) => { 
   // handle routes
   console.log(expressapp)
};

try {
  exports.configure();
} catch(err) {
  console.error(err)
}

const exports = {};

exports.configure = ({
   expressapp = null,
   userdb = null,
   path = '/myroute'
} = {}) => { 
   // handle routes
   console.log(expressapp)
};

try {
  exports.configure();
} catch(err) {
  console.error(err)
}
like image 99
guest271314 Avatar answered Oct 18 '25 02:10

guest271314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!