Tutorial

How To Use Destructuring Assignment In JavaScript

Published on December 12, 2019
author

Chris Nwamba

How To Use Destructuring Assignment In JavaScript

JavaScript provides you with the ability to destructure objects and assign the individual units in one take. This allows you to get to the point of what you want to do and keep things clean.

In brief, destructuring means to unpack the values of objects or arrays into variables. At the end of this guide, you will see how to use it and what it can replace for you.

Destructuring Arrays

Prior to the development of destructuring assignments, if you had an array and wanted to assign some of it’s values to variables, you would do something like this:

let johnDoe = ["John", "Doe", "Iskolo"]
let firstName = johnDoe[0]
let lastName = johnDoe[1]
let title = johnDoe[2]

console.log(firstName, lastName, title) // John Doe Iskolo

You can get the same result by destructuring the array, like this:

let johnDoe = ["John", "Doe", "Iskolo"]
let [firstName, lastName, title] = johnDoe
console.log(firstName, lastName, title) // John Doe Iskolo

This method allows you to pick any number of elements you want:

let johnDoe = ["John", "Doe", "Iskolo"]
let [firstName, lastName] = johnDoe
console.log(firstName, lastName) // John Doe

Or:

let johnDoe = ["John", "Doe", "Iskolo"]
let [, lastName, title] = johnDoe
console.log(lastName, title) // Doe Iskolo

You can do this with strings as well:

let [firstName, ,title] = "John Doe Iskolo".split(" ")
console.log(firstName, title) // John Iskolo

We can throw in the rest operator (...) to collect the rest of the arguments:

let [firstName, ...others] = "John Doe Iskolo".split(" ")
console.log(firstName, others) // John Iskolo

And we can even bring in objects here:

let johnDone = {}
[johnDoe.first, johnDoe.last] = "John Doe Iskolo".split(" ")
console.log(johnDoe.first, johnDoe.last) // John Doe

In Looping Through Objects

We can use destructuring assignment to loop through a key-value pair variable like an object or map:

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"
}
Object.keys(obj).forEach(key => {
  console.log(`${key} : ${obj[key]}`)
})

We can spin that differently like this:

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"
}
for(let [key, value] of Object.entries(obj)) {
  console.log(`${key} : ${value}`)
}

It might look like the same thing to you, but it is not. In using forEach above, we pull the keys of the object into an array, then looping through that array of keys now and using those keys to pick out the values of objects.

In the second part, we just go straight and loop through each object entries and extracting the keys and values.

Assigning default values We can assign defaults values, just for a situation where the variable we wish to destructure is empty:

let [firstName = "John", ,title = "Fire"] = "John Doe".split(" ")
console.log(firstName, title) // John Fire

Destructuring Objects

Like we did with arrays, we can destructure objects as well. If you have ever used React, you may have seen this used when importing a module.

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"
}

let {firstName, lastName) = obj
console.log(firstName, lastName) // John Doe

When destructuring objects, we use the keys as variable names. This is how JavaScript knows which property of the object you want to assign. Unlike arrays where you use their index/positions in the assignment, here you use the keys.

This destructuring works on any kind of object. If your object has nested values, you can still destructure that and extract the values into variables.

let obj = {
  name : "John Doe",
  address : {
    city : "Omsk",
    country : "Russia"
  }
}
let {city, country} = obj.address
console.log(city, country) // Omsk Russia

Using It To Pass Function Arguments

You may have seen functions that look like this:

function sumFunc(a = true, b = "", c = "", d = 0, e = false) {
  console.log(a,b,c,d,e)
}
// Call the function
sumFunc(true, "", "", "", true)
// Or if we want to preserve default values
sumFunc(true, undefined, undefined, undefined, true)

This doesn’t look so good. It gets worse if you are trying to perform a function like making a chart and you need a lot of arguments to create the chat.

In a situation like this, destructuring can be useful:

function sumFunc({a = true, b = "", c = "", d = 0, e = false}) {
  console.log(a,b,c,d,e)
}
let args = {a : false, e: true}
// Call the function
sumFunc(args)

By passing the function arguments as an object, they will get automatically resolved into independent arguments. Now, we pass an object with matching key-value pairs and the function will work nicely.

Conclusion

Destructuring is an operation you can do without, however, you can already see how it makes you a better developer. Cleaner code, fewer repetitions and more structure over what you have.

Use destructuring today and improve your code.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Chris Nwamba

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more