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.
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025