I'm spinning my head around this for a little while, but it seems I can't manage to make this work the way I would like it to. Actually, all I want here is to have nested default values for an optional argument. The output I'd like to see should be:
55, 44, { sub1: '0', sub2: 55, sub3: 'all'}
Instead, I just get this:
55, 44, { sub2: 55 }
Could somebody give me a heads up on this one?
function foo({ param1=55, param2=44, param3:param3 = { sub1:sub1='0', sub2:sub2=200, sub3:sub3='all' } } = { }) {
console.log(param1, param2, param3);
}
foo({
param3: {
sub2: 55
}
});
You are passing {sub2: 55} for param3, so it will not evaluate the default value { sub1:sub1='0', sub2:sub2=200, sub3:sub3='all' } (which is a literal here, not an assignment target, so wouldn't do what you think it does anyway).
If you want param3 to always be an object with 3 properties, constructed from the three default-valued variables, you have to build it explicitly yourself:
function foo({param1=55, param2=44, param3: {sub1='0', sub2=200, sub3='all'} = {}} = {}) {
var param3 = {sub1, sub2, sub3};
console.log(param1, param2, param3);
}
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