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

Alex Mata
3 min readOct 15, 2020

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:

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:

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.

The above function will return the following:

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

Alex Mata is a day dreamer and software engineer located in Houston, Texas. They enjoy expressing their creativity through code.