Blog

Front End Development topics with a touch of humor

Destructuring

What is this sorcery?

September 23, 2020


There is a pleasing symmetry to the basic ways of accessing array and object members.

        const arr = ['I', 'II', 'III', 'IV', 'V'];
        console.log(arr[1]);
        // I
        console.log(arr[5]);
        //V

        const dog1 = {name: 'Jupiter', breed: 'German shepherd', color: 'black', weight: 80};
        console.log(dog1.name);
        // Jupiter
        console.log(dog1.breed);
        // German shepherd
        

In both cases, the first part is the variable name of the outer part, the second part is the key or label of the inner part.

           arrayName + bracket + indexNumber + bracket
           // arr[1]

           objectName + dot + keyName
           or
           objectName + bracket + keyName + bracket
           // dog1.weight
           // dog1["weight"]
       

I like to imagine an array or object kind of like a motel. The array is the motel, the rooms are the parts inside it. The index or key is like the room number.

This is the basic way we all learn to access members. If we want the first member of an array called "arr," we write arr[0]. If we want the key called "breed" of the object dog1, we write dog1.breed or dog1["breed"]. Once we learn this, we happily go about our day, referencing arrays by their index and objects by their keys.

Then we run into code that looks like this:

        const arr = ['I', 'II', 'III', 'IV', 'V'];
        const [first, second] = arr;
       

What the heck is that supposed to mean? Is it even JavaScript? It looks sort of like JavaScript, but it's weird... Or maybe we see:

        const dog1 = {name: 'Jupiter', breed: 'German shepherd', color: 'black', weight: 80}; 
        const { color, weight } = dog1;
       

Again, it looks both like and unlike JavaScript... In both cases, we are seeing destructuring. We may vaguely recall this from early lessons in online tutorials, where it was briefly mentioned and soon forgotten. We may remember enough to know it's called "destructuring," but isn't coding hard enough already without these weird shortcuts?

I don't know about you, but I'd rather just type it out than learn this strange and confusing new syntax!

At least, that's how I originally thought about destructuring. It seemed an exotic technique for the cool kids, a flashy move to pull at CodeWars to show off for the noobs. It seemed to break the rule of making code easy to understand, as it made it harder to understand--for me, at least.

However, when I started learning React, I began to see destructuring all over the place, along with classes, and the ... operator. Reluctantly, I realized I was going to have to bite the bullet and learn this intimidating part of the language.

Learning to love the destructuring

What I found was that no amount of staring at the weird stuff helped. I needed to get my hands dirty. I only began to get it by writing a bunch of code.

I'm the kind of guy who learns by doing. A lot of people are, no? So let's do some destructuring, shall we? What we're going to do is write it out the basic way, then write it out the cool, slick, destructuring way. I suggest opening up the console and following along.

Arrays

First, let's do some array destructuring. First write out the normal way, then translate it to the destructuring way. You'll probably learn it better if you change the examples to suit your own interests. I always write about my dog, Jupiter, since he's usually at my feet or pestering me to play.

        const walkDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
        const [ firstDay, secondDay ] = walkDays;
       

The first part is a nomal array. The second statement uses destructuring. It doesn't make sense like a nice, normal assignment statement. x = 5 makes sense. dogBreed = "German Shepherd" makes sense. const [ firstDay ] = walkDays, not so much.

For me, it worked best to not think of it as "equals" "is assigned to," but just to think of firstDay and secondDay as new variables that correspond to the first and second array index numbers of walkDays. In other words:

        const firstDay = walkDays[0];
        const secondDay = walkDays[1];
       

is equivalent to:

        const [ firstDay, secondDay ] = walkDays;
       

It's a bit less typing, but a lot more confusing. Keep practicing. Break the association of "equals" that the = operator naturally has--it will lead you astray. The variables in the brackets correspond to the first and second variables of the array, walkDays.

Let's try another array.

        const lemonadeIncomeByMonth = [0, .50, .75, 2.00, 2.50, 6.25];
        const [ firstMonth, secondMonth, thirdMonth, fourthMounth, fifthMonth, sixMonth ] = lemonadeIncomeByMonth;        
        

This is the same as:

        const lemonadeIncomeByMonth = [0, .50, .75, 2.00, 2.50, 6.25];
        const firstMonth = lemonadeIncomeByMonth[0];
        const secondMonth = lemonadeIncomeByMonth[1];
        ... so on
        const sixMonth = lemonadeIncomeByMonth[5];
       

That saved me a lot of typing! This destructuring stuff is pretty cool!

Destructuring objects

You see a lot of destructuring objects in React.js code, one of the many things that makes it look rather alien to someone who mostly knows Vanilla.js. One of the patterns that puzzled me was this weird object stuff in a function parameter.

           function eatFruit({ apple, orange}) {
               return `${apple} is eaten. ${orange} is eaten.`;
           }
           const basket = { apple: "Delicious", orange: "Navel" };
           console.log(eatFruit(basket));
           // Delicious is eaten. Navel is eaten.
       

Again, it's all a little headspinny if you're used to accessing object values with the safe, comfortable technique of basket.apple or basket.orange, which just makes so much sense. So what's going on here?

If we look at the function arguments, we see it's expecting an object with the keys of apple and orange. The body then returns their value. It's equivalent to writing:

           function eatFruit(obj) {
               const apple = obj.apple;
               const orange = obj.orange.
               return `${apple} is eaten. ${orange} is eaten.`
           }
       

Not a huge savings in typing. Does it look a little cleaner, a little slicker? That's a matter of opinion, but I think so. According to AirBnB's style guide, Destructuring saves you from creating temporary references for those properties.

So we see in the old-fashioned way, we have to create a temporary reference, apple = obj.apple, whereas with destructuring, we can directly return the object property.

That might make sense, but it doesn't make it easy. The only way to get the hang of using destructuring is, well, to use it. So I suggest doing that. Put together your own problems. Write it out the old way, then transcribe it to the new way. When you're doing your own coding, do it both ways. With repetition, it will become second nature.

Happy destructuring!