I want to pass an object as an argument to the function. If property 'prop' of this object is undefined, it should be initialized by default value.
How to do it using modern JS?
I expect something like this:
const fun = function(options = { prop: 'default'}) { console.log(options.prop)}
fun({a: 'x', prop: 'hello'}) ... // log: 'hello'
fun({a: 'x'}) ... // log: 'default'
If you want to destructure in the parameter list, you won't have access to the entire original object (the options
, here) anymore - you'll only have the destructured variables. So, leave out the options =
part, and put the =
after the prop
, instead of :
. For example:
const fun = function({ prop = 'default', a }) {
console.log('prop:', prop, 'a:', a);
};
fun({
a: 'x',
prop: 'hello'
}) // log: 'hello'
fun({
a: 'x'
}) // log: 'default'
If the function also may not be called with any parameters, you may default-assign an empty object:
const fun = function({ prop = 'default', a } = {}) {
console.log('prop:', prop, 'a:', a);
};
fun({
a: 'x',
prop: 'hello'
}) // log: 'hello'
fun({
a: 'x'
}) // log: 'default'
fun(); // log: 'default'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With