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.
qux: () => 'qux'means to declareconst qux, whose value will be extracted as the propertyquxfrommyObject.However, if
myObjecthas no such property, the const is declared as if you'd just writtenconst qux = () => bar. Therefore, the default value ofquxis an arrow function.Note that for the default to be used, the
quxproperty must be absent or set to undefined inmyObject. The default will not be used ifquxinmyObjectis null or any other value.Also note that this will work:
But this will throw
ReferenceError: Cannot access 'bar' before initialization:This is because when you do
qux = () => bar, it's not attempting to access an undeclared variable yet. However, invokingqux()does attempt to access thebarvariable, so the order is important.