javascriptjavascript-objectsdestructuringobject-destructuring

How does dependent object destructuring assignment work in JavaScript?


This is apparently a valid destructuring assignment despite qux depending on bar:

const { foo, bar, qux = () => bar } = myObject;

How does this work since the documentation (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) does not cover how dependent assignments like the example above works.


Solution

  • qux: () => 'qux' means to declare const qux, whose value will be extracted as the property qux from myObject.

    However, if myObject has no such property, the const is declared as if you'd just written const qux = () => bar. Therefore, the default value of qux is an arrow function.

    Note that for the default to be used, the qux property must be absent or set to undefined in myObject. The default will not be used if qux in myObject is null or any other value.

    Also note that this will work:

    const { foo, qux = () => bar, bar, x=qux() } = {};
    

    But this will throw ReferenceError: Cannot access 'bar' before initialization:

    const { foo, qux = () => bar, x=qux(), bar } = {};
    

    This is because when you do qux = () => bar, it's not attempting to access an undeclared variable yet. However, invoking qux() does attempt to access the bar variable, so the order is important.