Introduction
We use JavaScript objects to store data and retrieve it later. We store data(aka information) in key-value
pairs. The key-value pair is also known as the object properties
.
Here is an employee
object with three properties: id, name, dept as keys and 007, 'James', and 'Spy' as values.
const employee = {
id: 007,
name: 'James',
dept: 'Spy'
}
Since ES6(ECMAScript 2015), JavaScript provides a mechanism to handle the properties of objects in a much more innovative way. The mechanism is called Destructuring
(also known as destructuring assignment). It is more of a new syntax added to the language than a feature.
If you like to learn from video content as well, this article is also available as a YouTube video tutorial here: 🙂
Don't forget to SUBSCRIBE for future content.
In this article, we will learn about the most crucial usages of object destructuring you must know as a web developer. It will make you a competent and efficient developer. If you know any other cool usages, don't forget to let us know in the comment section below.
⭐ Use destructuring to retrieve values from an object
The most basic usage of object destructuring is to retrieve the value of a property key from the object.
const employee = {
id: 007,
name: 'James',
dept: 'Spy'
}
Traditionally, we will use the dot(.) notation or the subscript([]) notation to retrieve values from the object. The code snippet below shows the example of retrieving the value of id
and name
from the employee
object using the dot notation.
const id = employee.id;
const name = employee.name;
No doubt it works perfectly. But think about the tiring typing(or copy-paste-edit) work when you have to do it for many property values? That's where the destructuring assignment syntax comes as a savior.
To destructure a value from an object, you use a syntax like this,
const { id, name } = employee;
Here, we use the object's key names to create variables and assign them with the value from the object for the same key. In the above code snippet, we retrieve the value of id
and name
without typing them in multiple lines.
Even if you have 20 more values to retrieve, it is just a matter of specifying those key names with commas. Such a relief!!!
⭐ Use destructuring to retrieve values from a nested object
In all practicality, your data object may not be as simple as the employee
object we have seen so far. The object's key can have another object as a value and form a nested object. Let us now see how to retrieve the value for a key from a nested object.
Here is our employee
object where the value of the dept
key is an object. It has a property with the key address
whose value is another object. Great, we are dealing with a nested object here.
const employee = {
id: 007,
name: 'James',
dept: {
id: 'D001',
name: 'Spy',
address: {
street: '30 Wellington Square',
city: 'Chelsea'
}
}
}
Let's retrieve the value of the address
property traditionally.
const address = employee.dept.address;
It works, and the output is,
{
"street": "30 Wellington Square",
"city": "Chelsea"
}
Now let us go one more level down and retrieve the value of the street
property.
const street = employee.dept.address.street;
Of course, we typed more, and the output is,
30 Wellington Square
Now with destructuring, things are simple. You can define the key name using its predecessor key. So to retrieve the value of address
, we will start with its predecessor key dept
. So, dept
is the top-level key with no predecessor. Hence the syntax is,
const { dept: { address } } = employee;
console.log(address);
and for the street
property,
const { dept: { address: { street } } } = employee;
console.log(street);
Let's move to the next one.
⭐ Define a new variable with object destructuring
There could be a situation where you are unsure if the object has a specific key while retrieving its value. Also, you may want to create a new variable with a default value in case the key is unavailable in the object.
Let's take this employee
object for an example,
const employee = {
id: 007,
name: 'James',
dept: 'Spy'
}
Now let's assume we are trying to retrieve the value of the age
property, which is not present in the object. A traditional way to do that is,
const age = employee.age ? employee.age : 25;
If we find the age
property, access its value, and assign it to the variable else, assign a default value of 25. So, how will we do that with the object destructuring syntax we have learned so far?
It is pretty simple.
const { name, age=25 } = employee;
console.log(age);
As you see, we can do it easily by specifying the key name along with the default value. It has a similar impact as the traditional way we have learned just now.
Hold on. The destructuring part has got more magic to show! How about creating a brand new variable and assigning a value computed using the object property values? Sounds complex? Here is an example,
const {name, dept, message = `${name} is ${dept}`} = employee;
console.log(message);
We create a message
variable and assign a value computed using name
and dept
property values of the employee
object. Powerful, eh?
The output is,
James is Spy
⭐ How to use JavaScript object destructuring aliases?
In JavaScript object destructuring, you can give your destructured variables an alias
name. It comes in very handy to reduce the chances of variable name conflicts.
const employee = {
id: 007,
name: 'James',
dept: 'Spy'
}
Let's assume your source code has an existing variable named dept
. So if we use the same variable name in destructuring, there will be a name conflict.
Instead, you can use an alias name to create the variable with this new name. For example, we can use the alias name department
in this case.
const { dept: department } = employee;
console.log(department); //Spy
Please note, we have destructured with the alias name, not with the actual key name that is still not defined.
console.log(dept);
Output,
I have shared this usage as a knowledge byte on Twitter a while back,
FOLLOW me on Twitter for more tips and content.
⭐ Handle dynamic name property with object destructuring
We often handle API response data as JavaScript objects. These objects may contain dynamic data such that, as a client, we may not even know the property key names in advance.
Let's understand it with an example(same employee object)
const employee = {
id: 007,
name: 'James',
dept: 'Spy'
}
Can we write a function that returns the value of the employee object properties when we pass a key as an argument? Yeah, so it means we will not hard-code the key name inside the function. It is dynamic for the function.
Here is the code snippet to showcase how we may call the function.
const id = getPropertyValue('id');
const name = getPropertyValue('name');
console.log(id, name); // 7 'James'
Let's define it now.
function getPropertyValue(key) {
const { [key]: returnValue } = employee;
return returnValue;
}
Please note the square brackets([..]) around the key
in the destructuring assignment. The key we pass to the function gets evaluated, and the value is retrieved from the object. Isn't that cool. It is efficient usage.
⭐ Destructure objects in the function argument and return value
You must learn this usage if you want to explore any modern JavaScript-based frameworks/libraries like React, Vue, Svelte, Angular, etc. You can use object destructuring to pass the property values as arguments to the function.
The employee object,
const employee = {
id: 007,
name: 'James',
dept: 'Spy'
}
Now let us create a simple function that creates a message using the name
and dept
property values to log into the browser console.
function logEmployee({name, dept}) {
console.log(`${name} is ${dept}`);
}
Just realize how simple it is. You don't need to take the entire object as an argument and pick the required property values. You pass the values directly as function arguments and use them inside.
You can now call the function as,
logEmployee(employee); // James is Spy
There is one more usage of object destructuring with function. If a function returns an object, you can destructure the values directly into variables. Let's create a function that returns an object.
function getUser() {
return {
'name': 'Alex',
'age': 45
}
}
Now if you are interested to retrieve the value of the age
property, you can do it like,
const { age } = getUser();
console.log(age); // 45
It indeed saves lots of extra typing and time.
⭐ Use object destructuring in loops
The last(but not the least) usage we will be discussing is destructuring in loops. Let's think of an array of employee objects. We want to iterate through the array and want to use the property values of each of the employee object.
const employees= [
{
'name': 'Alex',
'address': '15th Park Avenue',
'age': 43
},
{
'name': 'John',
'address': 'USA',
'age': 33
},
{
'name': 'Ravi',
'address': 'Bangalore',
'age': 16
}
];
You can use the for-of
loop to loop through the employees
object and then use the object destructuring assignment syntax to retrieve the details. Let us log the name and age of each employee in the browser console.
for(let {name, age} of employees) {
console.log(`${name} is ${age} years old!!!`);
}
Output,
That's so neat. We all love object destructuring by now.
Conclusions
Time is precious. The more you save on that, the more you can produce more. The object destructuring syntax is here to save you that time. Please use it in practice, if not already.
I'm thrilled to share my experiences on object destructuring with you using this article. Please let me know if you found it helpful. You can find all the source code used in this article from here,
Let's connect. I share my learnings on JavaScript, Web Development, Career, and Content on these platforms as well,
Top comments (24)
Nice 😎 this is an amazing and very useful feature. Another useful thing with object destructing is to destruct some properties and then use the spread operator to get the rest.
Since it is ..., it's not sread operator.
In Object Destructuring, these three dots is rest propertises,
Rest in Object Destructuring
The Rest/Spread Properties for ECMAScript proposal (stage 4) adds the rest syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.
Awesome Daniel, Thanks for adding to the list. Have a great day.
I was playing a bit with at(), but it's not supported in all browsers.
Mindblowing. Thanks, John for sharing.
Here's one more for you.
Super. Thanks!
A lot of times, you don't need destructuring. Reasons:
You can use aliases for the # 1 point.
2, agree but when you see the entire dev ecosystem(like with React I see) using it, I think, it is better to contribute that way.
Hey, thanks a lot for giving it a read and posting your views.
I would advise against variable definitions during destructing like this:
What you're actually doing here is simply defining a default value for employee's property
message
. So as a side effect if your object actually has a property with that name, it will simply override your default value.It works, and you could still use it, but be aware of what's actually happening and consider writing 1 line of extra code to prevent possible unexpected behaviour.
Apart from that – A good overview to destructing. Gj!
Awesome article! I use destruction all the time. Two things I find confusing tho is that nesting and alias share the colon operator (if you look closely they differ in syntax but I find it confusing). Same with default value and assignment to new attribute. So if you want to create a new attribute you need to make sure that one does never already exist on the object or you might get unwanted results.
~Cheers
Thank you! I completly agree.
Great! Thanks for sharing.
Welcmome 😀
Hi just testing the comment indentation levels on dev.to
Test passed? 😅
I'm building a blog site and im in the process of adding nested replies to comments, I wanted to see how the ui here handled nested comments. I wonder how far down you can go and will it keep indenting
12
Thanks for elaborating destructuring in loops and and default value.😃
It'll help me to improve my current project
That's great. Very glad to know, you found it helpful
Agree. The code needs to be human readable rather than concise. In any case the code gets compiled to a shorter form during build.
Awesome post
Thank you very much!