Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading