I want to have a function with default parameters inside nested objects, and I want to be able to call it either f() or specifying only individual parameters.
// A function with nested objects with default parameters:
function f({ a = 1, callback = ({ name, param } = { name: "qwe", param: 123 }) } = {}) {
    console.log("a:", a);
    console.log("callback:", callback);
}
// And I want to run it like this:
f();
f({ callback: { params: "456" } });
// But 'callback.name' becomes undefined.
When destructuring is mixed with default parameters, I admit the code is hard to read and write (especially when there are nested objects...).
But I think you are trying to do that:
function f({callback: {name = "cbFunction", params = "123"} = {}} = {}) {
  console.log(name);
  console.log(params);
}
f();
f({callback: {params: '789'}});
I found none of the answers here to be what he wanted. But it IS actually possible in a somewhat sexy way by doing this:
(EDIT: Simplified syntax and also show how to add default values for subobjects)
function f({
    a = 1,
    callback = {}
  } = {}) {
  callback = { // default values
    name: "cbFunction",
    params: "123",
    ...callback // overwrites it with given values
  }
  // do the same for any subobjects
  callback.subObject = {
    arg1: 'hi',
    arg2: 'hello',
    ...callback.subObject
  }
  console.log("a:", a)
  console.log("callback:", callback)
}
f()
f({a: 2, callback: {params: '789', subObject: {arg2: 'goodbye'}}})
Turned out to call it like this solves the problem, but is it the best way?
function f({
  a = 1,
  callback = ({
    name,
    param
  } = {
    name: "qwe",
    param: 123
  })
} = {}) {
  console.log("a:", a);
  console.log("callback:", callback);
}
f();
f({ callback: { name, params: "456" } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With