But when I try to use destructuring to define default values
constructor({id = 'defaultId', options = { op2:'0'}} = {}){
for one of the constructor parameters (op2, the property of options of nested objects), I cannot make it work, while for the id property of the object I can.
Default values ββwork only on one level of parameters / properties. If the argument or undefined not passed, {} will be used for the first parameter. If the object does not have an id property, 'defaultId' will be used. If the object does not have the options property, {op2:'0'} will be used. If you pass an object with the options property, the default value will be ignored.
So, if you want to get the default value for the op2 property of the object, if no such property was found in the object, you need to use the destructuring of the options object itself:
constructor({id = 'defaultId', options: {op1, op2 = '0', op3} = {}} = {}) { this.id = id; this.options = {op1, op2, op3}; }
source share