JavaScript object destructuring usages you must know
JavaScript supports the destructuring assignment since ES6. Let us know the essential usages of it.
Table of contents
- Introduction
- ⭐ Use destructuring to retrieve values from an object
- ⭐ Use destructuring to retrieve values from a nested object
- ⭐ Define a new variable with object destructuring
- ⭐ How to use JavaScript object destructuring aliases?
- ⭐ Handle dynamic name property with object destructuring
- ⭐ Destructure objects in the function argument and return value
- ⭐ Use object destructuring in loops
- Conclusions
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
array 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,