How To Destructure An Object Using Existing Variables in JavaScript

A simple way to reuse existing variables and avoid annoying naming conflicts

How To Destructure An Object Using Existing Variables in JavaScript

Destructuring an object is a simple and quick way JavaScript gives us to extract data from that object and store it in a variable. With this, you can get one or more variables from that object in a single line.

Before the ES6 revision, if you needed the value of an object property in a variable, you would do something like this:

const obj = {
  name: "jon",
  age: 18,
  lovesBurgers: true,
}

const name = obj.name
const age = obj.age
const lovesBurgers = obj.lovesBurgers

console.log(name) // prints "jon"
console.log(age) // prints 18
console.log(lovesBurgers) // prints true

This is fine, but as you can see, we get a new line for every new value we extract from the object. If we need a lot of variables, it can get a little unhandy pretty quickly. With object destructuring, you can now do the same thing like this:

const obj = {
  name: "jon",
  age: 18,
  lovesBurgers: true,
}

// destructuring assignment takes a single line of code
const {name, age, lovesBurgers} = obj; 

console.log(name) // prints "jon"
console.log(age) // prints 18
console.log(lovesBurgers) // prints true

And if we want all of the properties, and there are just too many of them, we can use the spread operator, like this:

const obj = {
  name: "jon",
  age: 18,
  lovesBurgers: true,
  numOfSiblings: 4,
  cookingLvl: "newb",
  cleanedBedroom: false,
  WeeklyTeethBrushes: 5,
}

// destructuring assignment takes a single line of code
const {name, age, lovesBurgers, ...otherStuff} = obj; 

console.log(name) // prints "jon"
console.log(age) // prints 18
console.log(lovesBurgers) // prints true
console.log(otherStuff) // a new object with all the other properties

This syntax makes for simpler, smaller code and improves both productivity and code readability. But as you can probably guess by the const keyword in front of the assignment, it creates new variables for every new destructured value. What if you want to update an existing variable? Maybe you have a perfectly fine, brand-new variable that's in very good shape and you're not ready to discard just yet. Or maybe (and more likely) destructuring the object will result in variables with the same name getting in conflict with each other and renaming them is too stressful of a task for you to do this late in the night.

What do we do?

Well, we can just leave out the const, right?

const obj = {
  name: "jon",
  age: 18,
  lovesBurgers: true,
}

let name = "John"
let age = 20
let lovesBurgers = false

// OH CRAP! We got a 
// Uncaught SyntaxError: Unexpected token '='
{name, age, lovesBurgers} = obj;

console.log(name)
console.log(age)
console.log(lovesBurgers)

Well, not so fast!

You see, every time JavaScript sees curly brackets in the main flow of the code (that is, outside another expression), it understands a new context is being created. For instance, when you declare a function, a loop, or a conditional statement, you'll use curly brackets to wrap its body, and that creates a new context. The variables inside this new context only exist inside the context and are invisible everywhere else.

So we have to make sure to tell JavaScript this is not the case, but actually, a temporary object that takes values from the object it's referencing in the assignment. What we have to do is make complex and ugly code to make sure this little tiny bit of code works and it'll be a pain and a lot of wasted time. Ugh!

No, wait. We don't have to do this?

No! Not at all!

It's just an extremely simple matter of wrapping the destructuring assignment with parentheses!

const obj = {
  name: "jon",
  age: 18,
  lovesBurgers: true,
}

let name = "annie";
let age = 20;
let lovesBurgers = false;

// wrapped in parentheses for glory and victory!
({name, age, lovesBurgers} = obj);

console.log(name) // prints "jon"
console.log(age) // prints 18
console.log(lovesBurgers) // prints true

Awesome! Now we can recycle all of our variables and be super eco-friendly!

Now, PLEASE PAY ATTENTION TO THIS: because this is kind of a hack, you'll have to pay attention to semi-colons. Parentheses aren't usually meant to be used this way, and if JavaScript catches them without semi-colons to make it explicit the previous expression is finished, it'll think you're trying to run a function and it'll throw all kinds of errors, depending on what came before.

const obj = {
  name: "jon",
  age: 18,
  lovesBurgers: true,
}

let name = "annie";
let age = 20;
let lovesBurgers = false 

// it thinks we're trying to run let lovesBurgers = false(...), so we get
// Uncaught ReferenceError: Cannot access 'lovesBurgers' before initialization
({name, age, lovesBurgers} = obj);

Now that you know how to make good use of that nice, perfectly reusable variable, go destructure all the objects you can find! Destructuring is cool and healthy and all the cool kids are doing it! Happy coding!