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?

Object destructuring, or the destructuring assignment syntax, is a way to pull elements out of an object with less typing in the long run. It becomes particularly helpful in React after typing the word “props” so many times that you can’t see straight, or when you have nested objects.

Syntax

So, let’s say we’ve got a basic object representing a trip to Italy (#2020…one can dream, right?):

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store