Destructuring in JavaScript is a powerful and one of the coolest features of ES6. It gains importance especially when you move on from Vanilla JavaScript and start learning Frameworks like React where you will find destructuring used in almost every single file! In this blog post, we will try to understand this handy feature and also look at some cases where you might consider using it.
What is Destructuring?
The main purpose of Destructuring is to help you to extract values from arrays or objects and assign them to variables in a concise and convenient way. The idea behind this is to take an array or object and break it down into smaller arrays, objects or variables.
Extracting elements from arrays or objects is easy but with destructuring, it gets much easier as it greatly improves your code readability and also reduce the lines of code you have to write.
Array Destructuring
Destructuring can be performed on Arrays as well as Objects. Let's first take a look on How can we implement it on Arrays.
Extracting values from Array
Suppose you were given an array of numbers and you were told to extract the first 3 numbers from the array. You would normally do it in this way:
const numbers = [1, 2, 3, 4, 5];
const first = numbers[0];
const second = numbers[1];
const third = numbers[2];
With Destructuring our work gets much easier as we can perform the same task with just one line of code. Have a look:
const numbers = [1, 2, 3, 4, 5];
const [first, second, third] = numbers;
//first = 1
//second = 2
//third = 3
In Line 2, You notice that we write the names of the variables, inside the square brackets []
on the left side of the =
sign and the numbers
array itself on the right side of the =
sign. The variables first
, second
and third
receive those values from the array in the order/position in which they were declared which means that the variable first
contains the first element of the numbers
array, second
points to the second element and the third
variable refers to the third element of the array.
Destructuring of elements from an array happens on the basis of position or indexes meaning the order in which we declare the variables, in the exact same order, they will receive the elements of the array.
Skipping values
You can also skip certain values if you don't need them like this:
const numbers = [1, 2, 3, 4, 5];
const [first, , third] = numbers;
// Here the second element get's skipped
//first = 1
//third = 3
In this case, the second element is skipped and the third element is assigned to the third
variable.
Using the "rest" operator
The rest operator (also known as the spread operator) allows you to specify a variable that will capture all remaining elements of an array.
This can be useful if you want to assign the remaining elements to a separate variable. Let's use the above example to understand. Suppose you wanted the first and second elements of the numbers
array but also want to store the rest of the numbers. You can do it by writing 3 dots: ...
before the name of the variable in which you want to store the rest of the elements of the array, Like this:
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...others] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(others); // [3, 4, 5]
In this example, the rest operator is used to capture all remaining elements of the numbers
array and assign them to the others
variable. The first
and second
variables are assigned the first and second elements of the array, respectively.
Real World Use Case
Let's see a real world use case where we use Destructuring to make our lives easier!
function sumAndMultiply(a, b){
return [a+b, a*b];
}
const array = sumAndMultiply(2, 3);
const [sum, product] = array;
console.log(sum); // 5
console.log(product);// 6
The function sumAndMultiply
receives 2 numbers a
and b
and returns an array whose first element is the sum of the 2 numbers and the second element is the product of the 2 numbers which is stored in the variable array
and later we destructure the array to extract it's elements to sum
and product
variables respectively.
If we had not used Destructuring, we would have to create 2 functions, one for performing the sum operation and another for performing the product operation, but with Destructuring, we could do this with much less code!
Setting Default Values
When destructuring an array, you can set a default value for a variable if the value being destructured is undefined. This can be useful in a number of scenarios, such as when the array being destructured may not have enough elements or when you want to provide a default value if the element being destructured is undefined.
Here's an example:
const arr = [1, 2, 3];
const [a, b, c, d = 4] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); // 4
In this example, the variable a
is destructured to have a value of 1
, b
is destructured to have a value of 2
, and c
is destructured to have a value of 3
. The variable d
is also destructured, but since there are no more elements in the array, its default value of 4
is used.
This example didn't make much sense? Don't worry, Here is a practical example:
Consider this code:
function sumAndMultiply(a, b, c){
if(c != 0)
return [a+b, a*b, a/c];
return [a+b, a*b]
}
const array = sumAndMultiply(2, 3, 0);
//Destructuring
const [sum, product, division = "Sorry, Division not possible"] = array;
console.log(sum);//5
console.log(product);//6
console.log(division);//Sorry, Division not possible
Here the sumAndMultiply
function accepts 3 numbers. If the third number is not 0, then the function returns an array containing the sum - a+b
, product - a*b
, and division - a/c
. But if c
is 0, then the function returns an array containing only the sum and product of the 2 numbers since division by 0 is not possible here.
At the time of destructuring, we provide the division
variable a default value of: "Sorry, Division not possible"
, which would come to use in case the third
variable is 0 and the function does not return any value which can be stored in division
variable.
In case the third parameter is not 0, the value of division returned by the function gets assigned to the division
variable.
const array = sumAndMultiply(2, 3, 2);//The third parameter is not 0
const [sum, product, division = "Sorry, Division not possible"] = array;
console.log(sum);//5
console.log(product);//6
console.log(division);//1
Object Destructuring
Now let's look at how we can perform Destructuring on Objects
Simple Destructuring
Suppose you have an object with several properties, that you want to extract and assign to variables. Normally you would do it like this:
const object = {
property1: value1,
property2: value2
};
const p1 = object.property1;
const p2 = object.property2;
console.log(p1);//value1
console.log(p2);//value2
With destructuring, you can achieve the same thing with just one line of code:
const object = {
property1: value1,
property2: value2
};
const { property1, property2 } = object;
Important Note on Object Destructuring
Important Note About Destructuring In case of Objects:
One thing to be noted here is that the name of the property you want to extract from the object and the name of the variable in which you want to store the respective value should be the same. This is because extraction of object properties does not happen on the basis of indexes (like it used to happen in case of Arrays), but on the basis of the names of the keys.
The properties property1
and property2
are extracted from the object
, and their values are stored in variables with the same names.
Let's take another example where you have an object with several properties and you want to extract them and assign them to variables. Without destructuring, you would have to do something like this:
const person = {
name: 'John',
age: 30,
job: 'software developer'
};
const name = person.name;
const age = person.age;
const job = person.job;
With destructuring, you can achieve the same result in a single line of code:
const person = {
name: 'John',
age: 30,
job: 'software developer'
};
//Destructuring. Note! - Name of object property = Name of variable
const { name, age, job } = person;
Renaming Variables
If the property names in the object don't match the variable names you want to use you can rename the variables like this:
const person = {
name: 'John',
age: 30,
job: 'software developer'
};
//Object Destructuring
//Storing object props in differently named variable
const { name: personName, age: personAge, job: personJob } = person;
console.log(personName);//John
console.log(personAge);//30
console.log(personJob);//software developer
When you want to store the object properties in a variable whose name is different from the name of the
key
of that object property, this method becomes useful!
Nested Destructuring in Objects
Nested destructuring in Objects refers to the process of destructuring an object that has other objects nested within it. It can be a useful way to extract values from complex data structures.
Here we have multiple person objects namely person1
, person2
, person3
and person4
inside a person
object. Suppose you want to extract the name
and home
properties of person3
. You can do it like this:
const person = {
person1: {
name: "Krish",
home: "West Bengal"
},
person2: {
name: "Keshav",
home: "Delhi"
},
person3: {
name: "Rohit",
home: "USA"
},
person4:{
name: "Adam",
home: "UK"
}
}
//Extracting name and home properties from person3 object which is present inside the parent - person object
const {person3: {name, home}} = person;
console.log(name);//Rohit
console.log(home);//USA
Using the "rest" operator
The rest operator (also known as the spread operator) allows you to specify a variable that will capture all remaining properties of the object. Use 3 dots ...
before the name of the variable to extract all the rest properties from the object, Like this:
const person = {
name: 'John',
age: 30,
job: 'software developer',
address: {
street: 'Main Street',
city: 'New York',
country: 'USA'
}
}
const { name, ...otherProperties } = person;
console.log(name);//John
console.log(otherProperties);
//otherProperties = { age: 30, job: 'software developer', address: { street: 'Main Street', city: 'New York', country: 'USA' } }
Practical Use Case
In this section of the blog post, we will visit a website called {JSON} Placeholder, which is a Fake API for testing. Here, we will make a GET
request to the API which will provide us an array of objects, where each object will contain information about a fake user, and we will use Destructuring to extract a few objects from the array and perform some actions on the user information. So follow along.
Step 1: Visit the {JSON} Placeholder website
Step 2: Copy the code for fetching users
Scroll down to this section of the website and copy the code provided
Here this code basically makes an HTTP request to the URL 'jsonplaceholder.typicode.comtodos/1' using the fetch()
function and logs the information it receives from the API into the console.
We will modify this code just a little bit so that instead of getting todos we will get information about the users. Like this:
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => console.log(json))
Step 3: Making the GET Request
If you want you can open up a code editor and write the code as mentioned below but for simplicity I will write code directly in the console.
Copy the above code and paste it into your console and press Enter.
You will see that we get an array of objects, where each object contains information of a user like name
, address
, company
, email
and so on.
Step 4: Using Array Destructuring
You see that we got an array containing 10 objects (length of array = 10) or information about 10 users. The task here is to use Destructuring to extract the first 3 objects out of the array or in other words the information about the first 3 users.
Copy and paste the following code into the console:
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => {
const [user1, user2, user3] = json;
console.log(user1);
console.log(user2);
console.log(user3);
})
In the above code, on receiving the array of users from the API, we are destructuring it to obtain the first 3 objects from the json
array and store it into the 3 variables, user1
, user2
and user3
.
Note that we are destructuring an array and not an object hence the variables will be inside [ ], i.e, square brackets instead of { } curly brackets!
Now, your console will look like this:
We are successfully printing the first 3 users which we had destructured from the array of 10 users.
Step 5: Object Destructuring
Now the next task is to extract the name
, phone
, email
and the city
and zipcode
of the first user (i.e, user1).
We can do this by writing the following code:
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => {
//Destructuring the array of 10 users
const [user1, user2, user3] = json;
//Destructuring the user1 object to obtain more information about user1
const {name, phone, email, address: {city, zipcode}} = user1;
console.log(name);
console.log(phone);
console.log(email);
console.log(city);
console.log(zipcode);
})
Note that at this line const {name, phone, email, address: {city, zipcode}} = user1;
We are destructuring an Object hence the variables will be inside curly brackets {}
PS: Make sure to write the whole code as mentioned above otherwise some mysterious errors might pop up!
Now Your console will look something like this:
If you reached here, Congratulations, You have successfully destructured the user1
object and extracted its properties!
Conclusion
Destructuring is a powerful and convenient feature in JavaScript that allows you to extract values from objects and arrays with a concise syntax. It can greatly simplify your code, particularly when working with large or complex data structures.
Nested destructuring adds an extra level of flexibility, allowing you to extract values from deeply nested objects and arrays in a single statement. It can be especially useful when working with APIs or other external data sources that return complex data structures.
Overall, destructuring is an important tool to have in your JavaScript toolkit, and is well worth learning and using in your projects. Whether you are just getting started with JavaScript or are an experienced developer, you will find destructuring to be a valuable addition to your programming skills.
With this we come to the end of the blog. I hope you liked it and learnt something valuable from this blog post, if so a like would be appreciated!
About Me:
Hey there, My name is Krish Jaiswal, I am a Computer Science student from India, currently learning about Web Development and making an attempt to share my learning in public. I am open for Development and Technical Writing roles. If you are interested in hiring me, drop an email here: krishvp4856@gmail.com
Connect with me here: