DEV Community

Cover image for 3 Powerful Examples of Destructuring Assignment

3 Powerful Examples of Destructuring Assignment

Laurie on June 11, 2019

ECMAScript is always adding new features that make our code more powerful. I even started a discussion about people's favorites. ...
Collapse
 
michi profile image
Michael Z

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...

Collapse
 
laurieontech profile image
Laurie

Awesome!

Collapse
 
kip13 profile image
kip • Edited

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

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

Destructuring is good for readability.

Collapse
 
laurieontech profile image
Laurie

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

Collapse
 
kip13 profile image
kip • Edited

In the array above you could:

const [{ data }, { status }] = [
  {
    data: {
      item: "this thing"
    },
  },
  {
    status: {
      num: 200
    }
  }
]
Thread Thread
 
laurieontech profile image
Laurie

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

Collapse
 
anpos231 profile image
anpos231 • Edited

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

({data: {item = 'I am default'} = {}} = {}) => {
   item
}
Collapse
 
laurieontech profile image
Laurie

Great addition!

Collapse
 
bradtaniguchi profile image
Brad

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!

Collapse
 
laurieontech profile image
Laurie

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!

Collapse
 
hisdewdnesss profile image
Various

Nice, learned a new trick from this :)

Collapse
 
fellipegpbotelho profile image
Fellipe Geraldo Pereira Botelho

Awesome!

Collapse
 
nirmalpatel59 profile image
nirmalpatel59

excellent

Collapse
 
roninjosue profile image
Reynaldo Josué Cano Bárcenas

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

Collapse
 
laurieontech profile image
Laurie

So glad it was helpful!

Collapse
 
arlopezg profile image
Alejandro López • Edited

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'
Collapse
 
laurieontech profile image
Laurie

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