The Dungeon Master’s Guide to Coding: Object Destructuring in JavaScript

The druid sighs as they size up the craggy gap. “That’s a solid 30 feet,” they think to themselves. After a moment of consideration, the druid walks over to a couple of trees.With a touch of their hands a flitter of magic races through the trunks as the wood begins to reconfigure itself into a makeshift bridge. The druid smiles and enjoys an apple as their magical logs fall into shape.

Coding often feels like magic. I mean c’mon, “invoking” functions??
Coders like to play with the weave of the digital world much like the mages of fantasy settings. Object destructuring in JavaScript was the latest digital magic I learned, and I was blown away by its utility.

Let’s say we have a variable called “thief” that is assigned an object.

I want to make it easier to work with the data inside the object, and I want to do so in a way that is non-destructive to our original object. I could take the time, and create variables for each bit of information, but ES6 provides us a wonderful, even magical time-saver via the destructuring assignment syntax.

Here is how we’ll use destructuring assignment syntax:

Image for post
Image for post

The names of the variables in the curly braces match the keys found inside the object on the right side of the “=”. Doing this will assign the value of the variable to the value of the key inside the object.

Now when I log the variables of stats, abilities, and attacks to our console I will see the following:

stats => { charName: 'Alex', strength: 12, speed: 17, mind: 8 }abilities => steal,sneak,lockpickingattacks => slice,sneak attack

How cool!!

But I’m not finished.

I want this thief’s name easily available, so let’s go another level deeper by doing the following to our brand-new stats variable:

Image for post
Image for post

So when I log charName to the console I will get this back:

Name: Alex

It’s even possible to destructure objects from within the argument of a function.

Image for post
Image for post

The above function will return the following:

Image for post
Image for post

The limits of object destructuring are seemingly endless!
I hope this explanation has cast light (heh. heh.) on this wicked bit of coding magic. With a little time and practice you’ll be casting Destructure Object with ease.

Thanks for reading through this blog! You can read more of my work here.
Also connect with me on
LinkedIn and Github :)

Alex Mata is a software developer located in Houston, Texas. He plays D&D and listens to vaporwave whenever he isn’t solving problems through coding.

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