Tutorial

How To Use Destructuring Assignment In JavaScript

DevelopmentJavaScript

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

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.

0 Comments

Creative Commons License