Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring and setting nested default values

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
  }
});
like image 298
jAndy Avatar asked Mar 21 '26 10:03

jAndy


1 Answers

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);
}
like image 91
Bergi Avatar answered Mar 23 '26 01:03

Bergi