Yes, it is possible!
Solution 1:
function foo({ foo = 'foo', bar = 'bar', baz: { propA = 'propA', propB = 'propB' } = {} }) { console.log(foo) console.log(bar) console.log({propA, propB})
Solution 2 (workaround):
function foo({ foo = 'foo', bar = 'bar', baz = {} }) {
You can even do this:
const func = ([{foo, bar: {a, b: BB, c: CC = 'c'} = {}} = {}], ...{0: rest0 = 0, 1: rest1 = '1'}) => { }
The above code is a complex example, I will use simpler examples to explain:
Example 1:
const f1 = ({x: varx}) => console.log(varx)
When you call f1(obj)
, obj.x
will be assigned to varx
in the f1
area
Example 2:
const f2 = ({xy: {x, y}}) => console.log({x, y})
Like f1
, but with {x, y}
instead of varx
, obj.xy
will be assigned {x, y}
, so x = obj.xy.x
and y = obj.xy.y
Example 3: Now add default options to create
const f3 = ({xy: {x, y} = {}}) => { }
Now you still need to pass obj
as an object, but you no longer need to provide obj.xy
If obj.xy
is undefined
, x
and y
are undefined
s
Example 4. Now let x
and y
have default values
const f4 = ({xy: {x = 'XXX', y = 'YYY'} = {}}) => { }
If obj.xy
you passed, it is undefined
, {x, y}
will be set to {x: undefined, y: undefined}
, but since x
and y
also have default values, x
will be 'XXX'
and y
will be 'YYY'
Example 4: "FORM OF ULTIMATE LIFE"
const f5 = ({xy: {x = 'XXX', y = 'YYY'} = {}} = {}) => { }
I think I no longer need to explain this: D