← flaviocopes.com

How to destructure an object to existing variables in JavaScript

Published Oct 25 2020

Psssst! The 2023 WEB DEVELOPMENT BOOTCAMP is starting on FEBRUARY 01, 2023! SIGNUPS ARE NOW OPEN to this 10-weeks cohort course. Learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much more! ✨

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.



I write books for developers 👇🏼

© 2023 Flavio Copes Flavio Copes made in Italy 🇮🇹 using Notion to Site Notion to Site