Array/Object Destructuring - JavaScript
Hey. In this blog, you're gonna learn about one of the best features of ES6(the standardized javascript) which is array/object destructuring, and also about the spread operator. These features are crucial if you want to develop a web using a front-end framework such as react and even if you don't want to use it they're incredibly useful for making your code so much cleaner and easier to work with. You might be thinking about what destructuring is. So let's get started with it.
Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Simply put, the idea of destructuring is to take an object or an array and convert it into smaller objects or smaller elements, or smaller variables. Let's first see it in arrays and then we will see it in objects.
Array Destructuring
Imagine we want to extract data from an array, without destructuring syntax this is how it will be done-
let marks = [ 75, 88,92 ];
let subject1= marks[0];
let subject2= marks[1];
console.log(subject1); // 75
console.log(subject2); // 88
We can see that when we want to extract data from an array, we have to do the same thing over and over again. Destructuring helps us do this task very easily. So the above code with destructuring syntax will look like this:
let marks = [ 75, 88,92 ];
let [subject1, subject2]=marks;
console.log(subject1); // 75
console.log(subject2); // 88
Notice that the variables are set from left to right. So subject1 variable gets the first item from the array, the subject2 variable gets the second item from the array, and so on.
Skipping Items in Array
What if we only want the third item from an array? This can be done using a comma separator.
let marks = [ 75, 88,92 ];
let [ , , subject3]=marks;
console.log(subject3); // 92
In the above code, we used comma separation twice to omit the first two items and then assign the third item to the variable subject3. We can also have only a second item assigned to a variable by omitting the first item using a comma.
let marks = [ 75, 88,92 ];
let [ , subject2]=marks;
console.log(subject2); // 88
Using Default Values
Default values can be assigned to the variables just in case the value extracted from the array is undefined:
let [subject1,subject2]=[94]
console.log(subject1); // 94
console.log(subject2); // undefined
//to avoid getting undefined we can use default values
let [subject1="marks not available",subject2="marks not available"]=[94]
console.log(subject1); // 94
console.log(subject2); // marks not available
Rest Items
What if we want to assign some of the array items to variables and the rest of the items in an array to a particular variable? In that case, the new rest parameter syntax (...param) added in ES6 can be used with destructuring to achieve this. Here is a simple example to do it:
let marks = [ 75, 88, 92, 86, 84 ];
let [subject1, subject2, ...rest] = marks;
console.log(subject1); // 75
console.log(subject2); // 88
console.log(rest); //[92,86,84]
In the above code, after assigning the first and second items to variable subject1 and subject2, we used the rest parameter syntax (...rest) to assign the remaining values to the rest variable as an array. Rest parameter syntax should always appear as the end parameter because it takes all the remaining values.
Combining Arrays
We can also add two arrays using destructuring.
let a=[1,2,3];
let b=[4,5,6];
let c=[...a,...b];
console.log(c); // [1,2,3,4,5,6]
Destructuring Assignment with Functions
We can return more than one value from a function inside an array and then use the destructuring syntax to store these values in different variables. Let's try it.
function sumAndMultiply(a,b){
return [a+b,a*b]
};
let [sum,multiply]=sumAndMultiply(2,6);
console.log(sum); //8
console.log(multiply); //12
Swapping values using destructuring
We can use the destructuring syntax to swap the values of variables:
let a = 3;
let b = 6;
[a,b] = [b,a];
console.log(a);//6
console.log(b);//3
We have now seen a lot in array destructuring. Let's move on to object destructuring.
Object Destructuring
Can't we extract data from an object and assign it to a variable without object destructuring? Yes. We can do it, but destructuring helps us to do it easily and saves us a lot of time, and also it makes the code looks clean. Let's see with an example.
- without object destructuring.
let person = { firstName: "Rahul", country: "India", job: "Developer"};
let firstName= person.firstName;
let country = person.country;
let job = person.job;
console.log(firstName); //"Rahul"
console.log(country); //"India"
console.log(job); //"Developer"
- with object destructuring.
let person = { firstName: "Rahul", country: "India", job: "Developer"};
let { firstName, country, job } = person
console.log(firstName); //"Rahul"
console.log(country); //"India"
console.log(job); //"Developer"
We can see that how easy and simple it is to extract data from an object using destructuring syntax. We no more have to repeatedly do the same thing which makes the code look tedious. Let's look at it in more detail.
Using Variables to get values
If we want to assign values of an object to a new variable instead of using the name of the property, we can do this with the syntax: [object_key]:[variable_name].
let person = { firstName: "Rahul", country: "India", job: "Developer"};
let { firstName : name} = person
console.log(name); //"Rahul"
Using default values
If we try to extract data with a property name that is not available in an object then it will return, a variable is undefined. We can pass default values that will be assigned to such variables instead of undefined.
let person = { firstName: "Rahul", country: "India", job: "Developer"};
let { firstName, age="NOT AVAILABLE"} = person
console.log(firstName); //"Rahul"
console.log(age); //"NOT AVAILABLE"
Assigning rest of an Object
We used the rest parameter syntax in the array destructuring above. It can also be used to pick up property keys that are not already picked up by the destructuring pattern. Those keys and their values are copied into a new object:
let person = { firstName: "Rahul", country: "India", job: "Developer"};
let { firstName, ...about} = person
console.log(firstName); //"Rahul"
console.log(about); //{country: "India", job: "Developer"}
Nested Destructuring
While destructuring, objects can be nested. In that case, we can use nested object destructuring.
let person = {
firstName: "Rahul",
country: "India",
job: "Developer",
address:{
city:"Bhopal",
state:"MP"
}};
let { firstName, address:{city,state} } = person;
console.log(firstName); //"Rahul"
console.log(city); //"Bhopal"
console.log(state); //"MP"
Combining two objects
You can also combine two using destructuring syntax.
let person= {
firstName: "Rahul",
job: "Developer"
};
let address={
city:"Bhopal",
state:"MP",
country:"India"
};
let data = {...person,...address};
console.log(data);
Destructuring in arguments
The most useful and important part of object destructuring is the ability to use it inside of arguments in functions. It is especially used while working with languages like react.
let person = {
firstName: "Rahul",
country: "India",
job: "Developer",
address:{
city:"Bhopal",
state:"MP"
}};
function displayName({firstName}){
console.log(`Name of the person is ${firstName} `)
}
displayName(person); //"Name of the person is Rahul "
I hope this blog helped you. Thank you for reading.
Keep Learning. Keep Growing.