Let’s say I’m using a method in this way:
const {a, b} = foobar()
// or...
const obj = foobar()
const {a, b} = obj
Is there a way from within the foobar
function to tell whether it’s result is being destructured immediately, or stored in a variable / constant? Or would it have no context at that point / in that scope, other than if you passed it in the arguments?
// Is this the only way?
const {a, b} = foobar({ isDestructured: true })
2
Answers
There is no such syntax to help you in JavaScript.
However, I think you can achieve what you want easily by using another function:
There is no way to know. A function call ends before the value can be used. The question only makes sense ifan assignment is evaluated before the function call. Yet that cannot be done, as the right-hand value is needed for the assignment.
The call
fn()
has to finish beforefoo
is assigned. Thus during the execution offn
it’s not possible to know what the type of assignment is. Nor should it matter. Consider:If
bar
is used consistently after this point then the code is effectivelyconst { bar } = fn();
yet the fictional "destructuring detection" would have to flag it as not destructuring. Or would it flag the execution offn()
as being used as part of destructuring? Ultimately, that falls uder the same problem that it requires foregknowledge of how the code would execute before it does in order to determine that.For more information: