1

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.

fibol80270
  • 23
  • 3
  • Note that your example is slightly misleading, `qux` will still be `() => 'qux'`. – Etheryte Nov 23 '22 at 00:10
  • @Etheryte Yes, I am aware of that. Perhaps my example is a little confusing because of that? – fibol80270 Nov 23 '22 at 00:11
  • Yep, it works from left to right, but since this is a function, it doesn’t evaluate the variable right away. `const { foo, bar, qux = () => baz } = myObject;` is just as valid, so is `const { foo, bar, baz = bar } = myObject;`. Note that these default values will be entirely ignored for property names that resolve to `undefined`, anyway. `const { foo, bar = qux, qux } = myObject;` works as long as `myObject.bar` does not resolve to `undefined`. `const { foo, baz = qux, qux } = myObject;` will not work. – Sebastian Simon Nov 23 '22 at 00:15
  • @SebastianSimon That makes a lot more sense after seeing your example of `baz = qux` rather than my example involving the function. – fibol80270 Nov 23 '22 at 00:19

1 Answers1

2

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.

Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
  • Right, suppose we have `const { foo, bar, qux = () => bar } = {};` so that `foo, bar = undefined` and `qux = () => undefined`. The result stays the same even if we have `const { foo, qux = () => bar, bar } = {};` despite `bar` coming after `qux`. How does the order work here? – fibol80270 Nov 23 '22 at 00:14
  • @fibol80270 that's a really interesting point, I'm adding something to my answer that will appear in a few seconds – Andrew Parks Nov 23 '22 at 00:31
  • Thanks, that covers all bases for me. Planning on using this with React for default props, so I wanted to make sure I fully understood its behavior before usage. – fibol80270 Nov 23 '22 at 00:45