# Destructure a JavaScript object to existing variables

> Learn how to destructure an object into existing variables in JavaScript by wrapping the assignment in parentheses, plus the semicolon trick you need.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2020-10-25 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/javascript-destructure-object-to-existing-variable/

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

```js
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:

```js
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:

```js
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):

```js
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:

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

to prevent [JavaScript](https://flaviocopes.com/javascript/) to be confusing code being on separate lines but not terminated by semicolons.
