I had this problem. I was calling a function to get some data:

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

const { a, b } = doSomething()

but I had the need to wrap this into an if block to only execute this line if the user is logged in, which moving the const declaration inside the if block made those variables invisible outside of that block.

So I wanted to declare those variables first, as undefined variables, and then updating them when the data came in.

The first part is easy:

let a, b

The “tricky” one comes next, because we remove the const before the object destructuring, but we also need to wrap all the line into parentheses:

let a, b

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

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

Plus, if you’re like me and you don’t like using semicolons, you need to add a semicolon before the line, to prevent possible issues with parentheses being around (and Prettier should automatically add it for you, too, if you use it):

let a, b

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

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

This is needed just like we need to do this when we have an IIFE (immeditaly-invoked function expression) like this:

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

to prevent JavaScript to be confusing code being on separate lines but not terminated by semicolons.

Download my free JavaScript Beginner's Handbook


HUGE PROMO LIVE NOW
Black Friday!