Skip to content

How to destructure an object to existing variables in JavaScript

New Course Coming Soon:

Get Really Good at Git

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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: