How to destructure an object to existing variables in JavaScript
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 all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.