How to deconstruct an object into an existing variable in JavaScript

I have this problem. I am calling a function to get some data:

const doSomething = () => {
  return { a: 1, b: 2 }
}

const { a, b } = doSomething()

But i need to wrap it toifThe block executes this line only after the user is logged in, thus movingconstStatement insideifThe block makes these variables invisible outside the block.

Therefore, I want to declare these variables as undefined variables first, and then update them as I enter the data.

The first part is simple:

let a, b

Next is the "tricky" because we removedconstBefore the object is decomposed, but we also need to wrap all the lines in parentheses:

let a, b

const doSomething = () => { return { a: 1, b: 2 } }

if (/* my conditional */) { ({ a, b } = doSomething()) }

Also, if you are like me and don’t like to use semicolons, you need to add semicolonsbeforeThis line to prevent problems around the brackets (if used, Prettier should also automatically add it for you):

let a, b

const doSomething = () => { return { a: 1, b: 2 } }

if (/* my conditional */) { ;({ a, b } = doSomething()) }

This is needed, just like when we have an IIFE (function expression called by immeditaly):

;(() => {
  //...
})()

Prevent JavaScript from obfuscating code that is on a separate line but does not end with a semicolon.

Download mine for freeJavaScript beginner's manual


More js tutorials: