Javascript (Node.js) destructure json into existing variables

Viewed 865

I'm wondering if it is possible to declare variables once in a method and then reuse them multiple times to capture destructured return values.

for eg:

  function verifyStatusAsSignedIn(url, cred){

     // code truncated

     return { 'error' : false, 'status': true }
  }

I can do declaration and destructure JSON at the same time.

 const { error , status } = verifyStatusAsSignedIn(url, cred);

But I have more methods that I call that will also return JSON with error and status just like the method 'verifyStatusAsSignedIn()' does.

I would ideally like to do this:

  let error, status;

  { error, status } = verifyStatusAsSignedIn(url, cred);

  //  handle or respond to error and status.

  { error, status } = nextStep(val1, val2);

  // handle or respond to error and status

But this gives me a lint warning 'Declaration or statement expected.

Is it possible to re-use existing variables to destructure a json object ?

1 Answers

You just have to surround it with parens like this to assign to existing variables:

let error, status;
({ error, status } = verifyStatusAsSignedIn(url, cred));

This is because without the parens, Javascript thinks the { is the start of a new block scope. It's apparently one place where the destructuring assignment syntax ran into a conflict with existing syntax rules so it takes a work-around with the parens to use it this way.

You can see MDN describe this situation here.

Related