Search code examples
javascriptdestructuring

Nested partial object defaults when destructuring in JS?


Consider the following code:

function foo({
    item1 = 'a',
    item2 = 'b',
    item3 = {x: 1, y: 2}
} = {}) {
    console.log(item1,item2,item3.x,item3.y)
}

If you call foo() you will get an object with the defaults for item1, item2, and item3. You can also call foo({item1: 'm', item2: 'n'}) and your result will include the default item3 of {x: 1, y: 2}. However, if you call:

foo({item1: 'm', item2: 'n', item3: {x: 99}})

you'll get undefined for item3.y in the scope of the function foo.

So:

Is there a way to get individual defaults for the nested properties of item3 in a scenario such as this?


Solution

  • This is not possible.

    In the parameters, you're trying to extract 3 variables: an item1 object, an item2 object, and an item3 object.

    On top of that, you're also trying to mutate the item3 object in case it doesn't contain a certain property.

    But all destructuring can do is extract properties from an object into variables - it cannot mutate any existing objects (without some really ugly wacky code that shouldn't be used).

    If you're OK extracting the individual properties of item3 into new variables, it would be quite possible, though:

    function foo({
      item1 = 'a',
      item2 = 'b',
      item3: {
        x = 1,
        y = 2
      } = {}
    } = {}) {
      console.log(item1, item2, x, y)
    }
    
    
    foo({item1: 'm', item2: 'n'})
    foo({item1: 'm', item2: 'n', item3: {x: 99}})