loading...
Cover image for 3 Powerful Examples of Destructuring Assignment

3 Powerful Examples of Destructuring Assignment

laurieontech profile image Laurie Originally published at tenmilesquare.com ・2 min read

ECMAScript is always adding new features that make our code more powerful. I even started a discussion about people's favorites.

In there, I listed that mine was destructuring assignment. You can read more about it in the mozilla docs.

So without further ado, here are some great examples of this syntax in action!

Object Destructuring

Let's say we have an object we want to manipulate that looks like this:

{
  data: {
    item: "this thing"
  }
}

If we pass it into a function and access item it's kind of messy.

(result) => {
   result.data.item
}

With destructuring assignment, we can change it to this!

({data}) => {
   data.item
}

Importing and exporting modules uses this concept quite a bit.

Array Destructuring

What if instead we had an array.

[
  {
    item: "this thing"
  },
  {
    num: 200
  }
]

Accessing it without destructuring assignment is less than ideal.

(result) => {
   result[0].item
}

But look how powerful ES2015+ is!

([data, status]) => {
   data.item
}

Together and with aliases!

I came across an amazing use case for destructuring assignment while using Promise.all the other day. If you aren't familiar, Promise.all resolves multiple promises and puts the results in an array. Something like

[result1, result2]

Now, think about a typical promise response (especially if it's an http request) both of the results likely look similar to this.

{
  data: {
    item: "this thing"
  }
}

We can combine both of our previous examples and make this a lot cleaner to access the content inside each response object.

Promise.all([
            promise1,
            promise2,
        ]).then(([{ data: result1 }, { data: result2 }]) => {
            result1.item
        });

Now, there are a number of things happening here.

  • We're using array destructuring to access each item in the array individually.
  • Then, we use object destructuring on those array entries.

But there is a twist. What is this?

{data: result1}

This is assigning a variable name to the data object. We don't want to use data because we're also accessing something called data in result2. Note that the object we're accessing goes first and the name goes second. The following wouldn't work.

Promise.all([
            promise1,
            promise2,
        ]).then(([{ result1: data }, { result2: data }]) => {
            result1.item
        });

You must have unique variable names (understandably). And in this example data is being used twice.

The Power

But there you have it. Look at how much cleaner our code can be with destructuring assignment!

Posted on Jun 11 '19 by:

laurieontech profile

Laurie

@laurieontech

Software dev at Gatsby | DC techie | Conference speaker | egghead Instructor | TC39 Educators Committee | Girls Who Code Facilitator | Board game geek | @laurieontech on twitter

Discussion

markdown guide
 

There is one more use case to destruct dynamically. Also resting!

let { [key]: id = 0, ...rest } = obj

I have written an article on it here: dev.to/mzanggl/let--key-id--0-rest...

 
 

The first example of Array destructuring isn't a valid array, close the object:

[
  {
    data: {
      item: "this thing"
    },
  },
  ...
]

Destructuring is good for readability.

 

Oops, this is what I get for typing directly in the article! I’ll make that fix.

 

In the array above you could:

const [{ data }, { status }] = [
  {
    data: {
      item: "this thing"
    },
  },
  {
    status: {
      num: 200
    }
  }
]

Yup! And that’s similar to the promise.all example.

 

You can also pass default values in case the property is not there:

({data: {item = 'I am default'} = {}} = {}) => {
   item
}
 
 

When I first started to learn destructuring I was very confused. Once I realized it was more like "back-ward assignment" I figured it out. Now I love using it!

Destructuring for the win!

 

I think of it like diving in a level deeper. You use bracket types depending on what type of data structure you’re trying to dive into.

Love that you love it now!

 

Nice, learned a new trick from this :)

 

Great information, I recently started learning ES2015 +, and destructuring is confusing for me. Thank you.

 

So glad it was helpful!

 

You can also set an alias to what you're destructuring!

const person = {
  name: 'John',
  lastName: 'Smith'
}

const { lastName: alias } = person

console.log(alias) // 'Smith'
 

Definitely! It's in that last example as well :)