DEV Community

Cover image for Javascript: Destructure Objects and Arrays for Cleaner Code
Anthony DiPietrantonio
Anthony DiPietrantonio

Posted on

Javascript: Destructure Objects and Arrays for Cleaner Code

The introduction of ES6 ushered in a handful of incredibly useful features for Javascript developers — one being of them being the ability to destructure arrays and objects.

https://media.giphy.com/media/ylyUQmwRhTyxiD5CFO/giphy.gif

What is destructuring and why should we care?

It will become clearer once you see some examples, but the beauty of destructuring is that it allows us to pull apart and pick out elements in an array or properties in an object for easier access in our code. Not only do we have the ability to quickly pull out distinct parts of arrays and objects, but it results in much simpler / easy to read code (most of the time).

https://media.giphy.com/media/THV1AH4dkSL56LHQ5O/giphy.gif

The Big Picture

Whether we destructure an array or an object, the syntax is nearly identical with some small caveats. The general idea is that to the left of our equal sign, we'll have brackets (for arrays) or curly braces (for objects), and to the right of our equal sign, we'll have the array or object that we are destructuring. Again, this will become clearer with the examples below.

Destructuring Arrays

Before destructuring, if we wanted to grab specific elements of an array, we would need to do something like this:

let fruits = ["🍎","🍊","🍌"]
let apple = fruits[0]
let orange = fruits[1]
let banana = fruits[2]
Enter fullscreen mode Exit fullscreen mode

With destructuring, we're now able to do the following:

let fruits = ["🍎","🍊","🍌"]
let [apple, orange, banana] = fruits

console.log(apple) // 🍎
console.log(orange) // 🍊
console.log(banana) // 🍌
Enter fullscreen mode Exit fullscreen mode

When destructuring arrays, if you decide you don't want to destructure a certain element, you still need to account for it by simply using back to back commas, to essentially skip over that element.

Meaning, if for whatever reason you did not want to destructure the second element in this fruits array you would need to do the following:

let fruits = ["🍎","🍊","🍌"]
let [apple,,banana] = fruits

console.log(apple) // 🍎
console.log(banana) // 🍌
Enter fullscreen mode Exit fullscreen mode

We can also make use of the rest parameter when destructuring arrays.

let fruits = ["🍎","🍊","🍌"]
let [apple, ...otherFruits] = fruits

console.log(apple) // 🍎
console.log(otherFruits) // ["🍊", "🍌"]
Enter fullscreen mode Exit fullscreen mode

Destructuring Objects

The real power of destructuring comes into play when using it with objects.

Before destructuring, if we wanted to grab specific properties of an object, we would need to do something like this:

let person = {
    name: "Tony",
    age: 55,
    occupation: "electrician"
}

let name = person.name
let age = person.age
let occupation = person.occupation
Enter fullscreen mode Exit fullscreen mode

With destructuring, we're now able to do the following:

let person = {
    name: "Tony",
    age: 55,
    occupation: "electrician"
}

let {name, age, occupation} = person

console.log(name) // Tony
console.log(age) // 55
console.log(occupation) // electrician
Enter fullscreen mode Exit fullscreen mode

We can even destructure nested objects, like so:

let person = {
    name: "Tony",
    age: 55,
    occupation: "electrician",
    family: {
        wife: "Maria",
        son: "Joe",
        daughter: "Amy"
    }
}

let {name, age, occupation, family: {wife}} = person

console.log(name) // Tony
console.log(age) // 55
console.log(occupation) // electrician
console.log(wife) // Maria
Enter fullscreen mode Exit fullscreen mode

We can even destructure objects within function parameters:

let person = {
    name: "Tony",
    age: 55,
    occupation: "electrician",
}

function describeThePerson({name, age, occupation}){
    console.log(`${name} is ${age} and is a/an ${occupation}.`)
}

describeThePerson(person) // Tony is 55 and is a/an electrician.
Enter fullscreen mode Exit fullscreen mode

https://media.giphy.com/media/iBjylURwS9N9FCl8Dl/giphy.gif

And just like that, you've cleaned up your code quite a bit and made it that much easier to read. Just remember when destructuring:

  • Arrays
    • use brackets [ ]
    • if you don't plan on using a certain element, skip over it by not including a variable name (thus resulting in back to back commas)
  • Objects
    • use curly braces { }
    • you can freely pick and choose which properties you want to use
    • for nested objects
      • type out the key, add a colon, then follow it with another pair of curly braces { }, and finally mention the nested key you want inside of the curly braces

This was a simple breakdown of destructuring and some of the most common ways to use it.

As always, refer to MDN for more info:
Destructuring

Feel free to reach out on any of my socials for questions, feedback (good and bad), or just to connect / say hello 👋.

Top comments (4)

Collapse
 
abdurrkhalid333 profile image
Abdur Rehman Khalid

This is a very beautiful article written to explain a very beautiful use of one of the most powerful features of modern JavaScript. But there are somethings that you have missed and I would like to make you aware of those things as well.

Missing a Value

If you want to miss the value at a certain index you can only place a simple "," there to skip that value and work with the rest.
To Miss the Value

Writing the Default Value

If there is no value being passed then you can also assign the default value as well.
Adding Default Value

Collapse
 
antdp425 profile image
Anthony DiPietrantonio

Yes, great comment -- thanks for adding it 😎

I originally chose to leave these out just so that I could cover the basics of the feature

Collapse
 
suraj__ profile image
Suraj

Excellent share. TFS. 😇

Collapse
 
antdp425 profile image
Anthony DiPietrantonio

Glad you liked it 😎!