Understanding destructuring in JavaScript
Unpacking values from objects? Destructuring arrays? Let's learn more about it!
Destructuring assignment in JavaScript is a convenient way to extract values from objects and arrays and then set them into new variables.
But, what's so interesting about it?
Well my friend, it allows us to access properties from nested objects, extract multiple values and even set a default one if it doesn't exist!
Let's see a before and after using object destructuring:
const marvel = {
name: 'spiderman',
realName: 'Peter Benjamin Parker'
};
So to get the name and the realName we'd have to do something like this
const name = marvel.name
const realName = marvel.realName
Now let's look how useful it is to use destructuring syntax to assign the value without having to repeat the property we're calling in just one statement!
Object Destructuring
const marvel = {
name: 'spiderman',
realName: 'Peter Benjamin Parker'
};
const {name, realName} = marvel
//name -> spiderman
//realName -> Peter Benjamin Parker
Wait Yuri, can i see a closer comparison?
Sure thing, my friend!
const name = marvel.name
const realName = marvel.realName
//becomes
const {name, realName} = marvel
Think of it as {property, property} = object that contains it
Undefined Value
If the object doesn't have the property it's looking for when using the destructuring assignment the value will return undefined.
Let's see how:
const marvel = {
name: 'spiderman',
realName: 'Peter Benjamin Parker'
};
const {transportation} = marvel
//undefined
It returns undefined because the transportation property doesn't exist in the object.
But, isn't there a way to assign value to it from the destructuring assignment?
Yes! You can set a default value to it.
Default Value
We can set a default value for transportation so that when we're looking for the property it doesn't return undefined.
They provide a fallback if nothing is found in the object.
const marvel = {
name: 'spiderman',
realName: 'Peter Benjamin Parker'
};
const {transportation = 'webs' } = marvel
//transportation -> webs
We have now succesfully assigned a new value and property to our object using Destructuring!! Isn't this fun?
But what if we want to change the name of the variable while we're at it?
Assign new names
It's possible for you to change the name of the variables you're working with when extranting their values.
We use a colon for it ( : ) !
Let's see the syntax together:
old name : new name
So if we take our spiderman example and change the name property for madeUpName it'll look something like this:
const marvel = {
name: 'spiderman',
realName: 'Peter Benjamin Parker'
};
const {transportation = 'webs' } = marvel
const {name:madeUpName } = marvel
//madeUpName -> 'spiderman'
You can also do it with multiple variables placing a comma ( , ) in the middle.
Let's change his real name to a secret name, gotta keep the 'hidden identity' hidden, right?
const marvel = {
name: 'spiderman',
realName: 'Peter Benjamin Parker'
};
const {transportation = 'webs' } = marvel
const {name:madeUpName, realName:secretName } = marvel
//madeUpName -> 'spiderman'
//secretName -> 'Peter Benjamin Parker'
Accessing values from nested objects
This is how most of the data is usually presented. Destructuring can help us get to those deep levels of objects to get what we want!
How do we do that? Well, let me show you:
const marvel = {
name: 'spiderman',
realName: 'Peter Benjamin Parker',
school: {
currently: 'Midtown School of Science and Technology'
}
};
const {school: {currently}} = marvel
//currently -> 'Midtown School of Science and Technology'
If we were to look for multiple properties we can! Just using a comma ( , ) .
There's no limit on how deep we can go into a nested object, you just need to keep adding nested curly braces ( {} ).
const { NestedObject: { propertyA: { propertyB: { .... } } } } = object;
We can see that the syntax to access properties in nested objects is
const {holdsNestedObjectWeWantThePropertyFrom:{propertyNameToAccess}}= object
Quite interesting, isn't it? We can also change the name of variables when working with nested objects!
Assign new names on nested objects
We do this the same way we did before, only keeping in mind that we need to do it in the object we want the variable to change.
const marvel = {
name: 'spiderman',
realName: 'Peter Benjamin Parker',
school: {
currently: 'Midtown School of Science and Technology'
}
};
const {school: {currently:actually}} = marvel
//actually -> 'Midtown School of Science and Technology'
Object as function parameters
Object Destructuring can be used to assign parameters to functions too!
You can destructure the object in a function argument.
function person({name: x, job: y} = {}) {
console.log(x);
}
person({name: "Peter"}) // -> Peter
The Rest Parameter in object destructuring
The Rest parameter is represented by three dots ( ... )
It helps us catch all the other elements we didn't with destructuring!
Take a look:
let person = {
name: "Peter",
country: "USA",
transportation: "web",
friends: ["Ned", "Gwen"]
};
let {name, friends, ...others} = person;
//console.log(name) -> "Peter"
//console.log(friends)-> ["Ned", "Gwen"]
//console.log(others) -> {country: "USA", transportation: "web"}
⚠️Even when the Rest Parameter looks exactly like the Spread Operator it's important not to get them mixed up.
We've seen objects so far but we can also use destructuring assignment on arrays!
Destructuring Arrays
We can see how powerful destructuring is in arrays when we need to extract data from them.
Without destructuring we'd do something like this, over and over again to get all the data we want:
let introduction = ["Your", "Friendly", "Neighborhood", "Spiderman"]
let first = introduction[0]
let name = introduction[3]
//console.log(first) -> "Your"
//console.log(name) ->"Spiderman"
With destructuring:
let introduction = ["Your", "Friendly", "Neighborhood", "Spiderman"]
let [first, adjective] = introduction
//console.log(first) -> "Your"
//console.log(adjective) -> "Friendly"
Even better! We could even do this with destructuring:
let introduction = ["Your", "Friendly", "Neighborhood", "Spiderman"]
let [first,,, name] = introduction
//console.log(first) -> "Your"
//console.log(name) ->"Spiderman"
Woah!! Wait up!! What did you do there with the commas?
Skipping items in the Array
When we want to skip values in an array we use the comma separator.
Do i need to skip values consecutively?? Not at all, my friend!
Let's say we want to skip the first and third value, we'd do something like this:
let [,adjective,,who] = ["Your", "Friendly", "Neighborhood", "Spiderman"]
//console.log(adjective) -> "Friendly"
//console.log(who) -> "Spiderman"
And if we want to skip all the values?
Use this:
let [,,,,] = ["Your", "Friendly", "Neighborhood", "Spiderman"]
Assign variables
We could even declare variables before assignment.
⚠️ It's important to remember that they are set from left to right so the first variable gets the first item and so on.
let adjective, where
[adjective, where] = ["Friendly", "Neighborhood", "Spiderman"]
//console.log(adjective) -> "Friendly"
//console.log(where) -> "Neighborhood"
The Rest Parameter
What if we want to store them in separate arrays when we assign them to a variable?
We use the Rest Parameter represented by three dots-> ( ... )
let [first,...sentence] = ["Your", "Friendly", "Neighborhood", "Spiderman"]
//console.log(first) -> "Your"
//console.log(sentence) -> "Friendly", "Neighborhood", "Spiderman"
This will create two arrays, one called first and the other one called sentence.
⚠️The Rest Parameter looks exactly like the Spread Operator but DON'T get them mixed up. The Rest parameter is used for destructuring and extracting data.
Swapping values with the Destructuring Assignment
We can also use it to swap values on variables!
let a = spiderman
let b = ironman
[a,b] = [b,a];
//console.log(a) -> ironman
//console.log(b) -> spiderman
Combining Arrays and Objects
They can both be used in destructuring, even together!
let person = {
name: "Peter",
country: "USA",
friends: ["Ned", "Gwen"]
};
let {name:superhero, friends: them} = person;
//console.log(superhero) -> "Peter"
//console.log(them) -> ["Ned", "Gwen"]
Conclusion
Destructuring is a very useful feature in JavaScript when we're in need of extracting data, being able to do so with multiple properties in one statement and even accessing nested properties!
This is one of those topics that will make your code less tedious to write and will give you the knowledge you need when using data.
I really hope you learned something new today!
Thank you for reading!! :)
Don't hesitate to contact me and let me know if you'd like to add something else in the comments.
☕If you enjoy my content Buy me a coffee It'll help me continue making quality blogs💕
💙Follow me on Twitter to know more about my self-taught journey!
💜Make sure to check out more articles on my JavaScript For Newbies Series
❤️Also subscribe to my Youtube Channel !
🖤And for more content and tips on TikTok !