I am trying to figure out if it is possible to handle several levels of default parameters with destructuring. Since this is not easy to explain in words, here is a step by step example ...
1 - Dismantling a flat object with default parameters
Restructuring this object is very simple:
let obj = {
foo: 'Foo',
bar: 'Bar'
};
C {foo = 'Foo', bar = 'Bar'} = {}in the function signature, the object will be created if there is no argument passed when the function was called. If the object is passed, but some reference properties undefined, they will be replaced with their default values. This code works fine:
function fn1({foo = 'Foo', bar = 'Bar'} = {}) {
console.log(foo, bar);
}
fn1();
fn1({foo: 'Quux'});
fn1({bar: 'Quux'});
fn1({foo: 'Quux', bar: 'Quux'});
Run codeHide result2 - Restructuring nested objects with shallow default settings
Destructuring this object is more difficult:
let obj = {
foo: 'Foo',
bar: {
quux: 'Quux',
corge: 'Corge'
}
};
{foo = 'Foo', bar = 'Bar'} = {} , {foo = 'Foo', bar = {quux: 'Quux', corge: 'Corge'}} = {} . , , (foo bar). , undefined (foo bar) .
, bar (quux corge) " ". , quux corge undefined, , bar :
function fn2({foo = 'Foo', bar = {quux: 'Quux', corge: 'Corge'}} = {}) {
console.log(foo, bar.quux, bar.corge);
}
fn2();
fn2({foo: 'Quux'});
fn2({bar: {quux: 'Baz'}});
fn2({foo: 'Quux', bar: {corge: 'Baz'}});
Hide result3 -
, " ". , :
function fn3({foo = 'Foo', bar = ({quux = 'Quux', corge = 'Corge'} = {})} = {}) {
console.log(foo, bar.quux, bar.corge);
}
fn3();
fn3({foo: 'Quux'});
fn3({bar: {quux: 'Baz'}});
fn3({foo: 'Quux', bar: {corge: 'Baz'}});
Hide result
, ES6. , ?