skip to Main Content

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


  1. There is no such syntax to help you in JavaScript.

    However, I think you can achieve what you want easily by using another function:

    function thatReturnsComplexOutput() {
        return {a: 'some', b: 'thing'};
    }
    
    function thatReturnsOnlyA() {
        return thatReturnsComplexOutput().a;
    }
    
    const simpleVar = thatReturnsOnlyA();
    const {a, b} = thatReturnsComplexOutput();
    
    Login or Signup to reply.
  2. 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?

    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.

    const foo = fn();
    

    The call fn() has to finish before foo is assigned. Thus during the execution of fn it’s not possible to know what the type of assignment is. Nor should it matter. Consider:

    cosnt foo = fn();
    
    const { bar } = foo;
    

    If bar is used consistently after this point then the code is effectively const { bar } = fn(); yet the fictional "destructuring detection" would have to flag it as not destructuring. Or would it flag the execution of fn() 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:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search