Destructuring and setting nested default values

816 views Asked by At

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
  }
});
2

There are 2 answers

4
Bergi On BEST ANSWER

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);
}
1
Rob M. On

Default parameters only get assigned if the parameter is empty. I think you need to use Object.assign in the body of the function:

const defaults = { sub1:sub1='0', sub2:sub2=200, sub3:sub3='all' }
function foo({ param1=55, param2=44, param3 } = { }) {
  const myParam3 = Object.assign({}, defaults, param3);
  console.log(param1, param2, myParam3);
}

foo({
  param3: {
    sub2: 55
  }
});