Object Destructuring in JavaScript

Photo by Clément Hélardot on Unsplash

As I have continued on my JavaScript learning from newbie to whatever is a little better than newbie, there have been certain concepts and syntactical sugar that I have avoided learning. The first was ternary conditionals, which I was forced out of my comfort zone to familiarize myself with while learning React. The next one, which I have dug in my heels about until now is object destructuring.

What is object destructuring?


So, we’ve got an object that is nested with various objects and arrays. But what if we want to grab the hotel we’re staying at in Naples? Is there an easier way than italianVacation.stops[“Naples”].hotel? This is where object destructuring comes in. Step one would be destructuring out the key-value pairs in the largest object.

Now, if we console.log startDate, we would get “06–01–2022”, and so on and so forth. The trick is to wrap these new variables you are defining inside the curly braces, and the name of the larger object you are trying to destructure on the right side of the equal sign. And from there, we can go even further inside of the nesting:

First, I broke down the stops by naming them by city, then grabbed Naples and broke down its key-value pairs of sight and hotel. Now, both hotel and italianVacation.stops.Naples.hotel will return “Romeo Hotel”.

Starting to see how this comes in handy, huh? Honestly, this is so simple that I’m a little ashamed that I waited so long to play around with it.

There aren’t many rules with this one…you don’t even need to name the variables the same thing as the key name (but I tend to for practical purposes).

This is just the basics of destructuring…you can also use this for arrays (with square brackets instead of curly braces) and there are a lot more advanced ways to use this to your advantage as well. For more information, I’d highly recommend checking out the documentation on MDN.

Blaire is a musical theatre performer who also moonlights as a full-stack software engineer. https://www.linkedin.com/in/blaire-baker