javascriptecmascript-6

Destructure a function parameter subproperty


I've got a Function that I want to be able to call in 2 ways, i.e alter it's signature - and it should behave the same.

Is there any ES6 syntax that will allow me to call the function doBar below using both ways with the same result?

Consider a function like this:

const doBar = ({ foo = 'bar' }) => {
  console.log(foo) // should log 'baz'
}

I'm using a framework that binds events like so:

<x-component on-some-event="doBar"></x-component>

which will essentially cause an invocation like so:

// where e = { detail: { foo: 'baz' } }
doBar(e)

.. but I'd like to be able to both call my Function explicitly as well, albeit with a proper call signature like so:

doBar({ foo: 'baz' })

Solution

  • You can use a default parameter. If foo is not found, it will use the value of detail.foo.

    const doBar = ({ detail = {}, foo = detail.foo }) => {
      console.log(foo) // should log 'baz'
    }
    
    doBar({ foo: 'baz' })
    
    
    doBar({
      detail: {
        foo: 'baz'
      }
    });