Welcome✌, everyone to Part-2 of How to use Destructuring in JavaScript. In this part, we will cover all about how to destructure an object.
Destructuring is important as many developers make use of it while extracting the value of a property from an object which we get from an API. Most of the time while working with AJAX ( Asynchronous JavaScript and XML) we fetch data from an API by providing an URL. After that, the API gives data in JSON data format which we convert to object using ".json()". The data is in form of an object and to get the value of a specific property of object we use Destructuring.
Table Contents :
- Why use Destructuring and What is its syntax?
- Difference between Destructuring an Array and Object
- Default Values
- Mutating Variables
- Nested Objects
- Quiz
Why use Destructuring and What is the syntax?
Hypothetical Situation: You are making a web app for a hospital 🏥to display data about the history of the patients. Now you are creating a feature where the doctor👩⚕️ can extract the history of patients 😷. And each patient's history is kept in form of an object.
Normally a developer who does not know destructuring will use the conventional way.
const sam ={
fullName:"Sam Williams",
age:23,
sex:"male",
allergies:["pet allergy","latex allergy"],
surgeries:null,
hereditaryDiseases:"Diabetes"}
const patientAllergies=sam.allergies;
const patientSurgeries=sam.surgeries;
const patientAge=sam.age;
console.log(patientAllergies,patientSurgeries,patientAge);//["pet allergy", "latex allergy"], null, 23
So this was the long process of getting the values into variables. Let's now do it with help of destructuring.
const sam ={
fullName:"Sam Williams",
age:23,
sex:"male",
allergies:["pet allergy","latex allergy"],
surgeries:null,
hereditaryDiseases:"Diabetes"}
const {allergies:patientAllergies,surgeries:patientSurgeries,age:patientAge}=sam;
console.log(patientAllergies,patientSurgeries,patientAge);//["pet allergy", "latex allergy"], null, 23
Destructuring reduces the amount of code we have to write and also made our code more efficient. Don't worry if you didn't understand anything once you will observe the syntax below and revisit this example your doubts will get clear.
Syntax
If we want to get the value of the property and assign it to a variable having the same name as the property name then we use the following syntax.
const {property1name,property3name,property2name}=object;
// The object on the right has more than or equal to 3 properties
// Or the property which is absent in the object gives output as undefined
Example on basis of our code written for our Medical🏥 history taking app
const sam ={
fullName:"Sam Williams",
age:23,
sex:"male",
allergies:["pet allergy","latex allergy"],
surgeries:null,
hereditaryDiseases:"Diabetes"}
// Please have a look at how we destructure the object sam
const {fullName,sex,age}=sam;
console.log(fullName,sex,age);//"Sam Williams", "male", 23
But what if you don't want name of the variable same as the property name in the object. Then we can assign the variable name of our own and the syntax is as follow:
const {property1name:variable1name,property3name:variable3name,property2name:variable2name}=object;
Example on basis of our code written for our Medical🏥 history taking app
//Consider sam object here from our previous examples
const {fullName:patientName,sex:patientSex,age:patientAge}=sam;
console.log(patientName,patientSex,patientAge);//"Sam Williams", "male", 23
Note: We can see here the order in which we keep the property inside the destructuring assignment doesn't matter.
Difference between Destructuring an Array and Object
First of all, if you want to know how destructuring works in the case of an Array I would recommend you to read the whole Part-1 of this blog series. Doing this will help you to understand the concept of destructuring completely.
How to use De-structuring in JavaScript?[Part-1]
If you have read Part-1 and remembers🤔 that we used to use square brackets '[ ]' on the left-hand side ◀of the assignment operator '=' to destructure an array. While destructuring an object we use curly brackets '{ }' instead of square brackets '[ ]'.
In array, if we don't want any variable then we used to just skip the variable by leaving a blank space inside the destructuring assignment as the order is important in the array. But in the case of an object, the order is not important thus we don't need to leave any space if we want to skip any variable we would not mention it inside the destructuring assignment.
Default Values
In the introduction as I said the destructuring is useful while we get data from an API. But most of the time we don't know if the value is present for that particular property as it comes from an API.
So for this, we preset the value of the variable to a default value while destructuring. Let see how to do it.
const sam ={
fullName:"Sam Williams",
age:23,
sex:"male",
allergies:["pet allergy","latex allergy"],
surgeries:null,
hereditaryDiseases:"Diabetes"}
const{smoking:"false",allergies:patientAllergies=null}=sam;
console.log(smoking,patientAllergies);//"false", ["pet allergy", "latex allergy"]
Here we can see we added default values for a property that checks the previous smoking history of a patient which is assigned default to "false" value and for property for which we have given our name called "patientAllergies".
As we can see there is no property called smoking in the sam object so we got default value for the smoking property and patientAllergies as it has some value in sam object it gets that respective value.
Mutating Variables
Destructuring can be also used for switching the value of the variables and this was also explained in Part-1 under the title Switching Variables.
let a=111;
let b=222;
const alphanum={a:97,b:98,c:99};
({a,b}=alphanum);
console.log(a,b);//97 98
Note:We need to use parathesis "( )" or we get error ( Uncaught SyntaxError: Unexpected token '=') as { } is sign of a code block and no code block can be assigned like shown in the code.
Nested Objects
If we have a nested object then we can use nesting inside the destructuring assignment (i.e. Destructuring inside destructuring.) to extract the values of properties of the nested objects into variables. Here is an example to explain that
const park={
name:"Nana Nani Park",
location:"Girgaon Chowpatty, Mumbai",
timings:{
mon:{open:"7am",close:"8pm"},
tue:{open:"7am",close:"8pm"}**,
wed**:{open:"7am",close:"8pm"}**,
thu**:{open:"7am",close:"8pm"}**,
fri**:{open:"7am",close:"10pm"}**,
sat**:{open:"7am",close:"10pm"}**,
sun**:{open:"7am",close:"11pm"}},}
const {timings:{mon:monTime}}=park;
console.log(monTime);//{ close: "8pm", open: "7am"}
In this example we have done destructuring in destructuring but as we can see there is extensive nesting done in this object and we can go further with destructuring it. We could also get the specific value of closing and opening time on Monday.
const {timings:{mon:{open:monOpenTime,close:monCloseTime}}}=park;
console.log(monOpenTime,monCloseTime);//"7am", "8pm"
Quiz
Now you have learned everything related to Destructuring of an object. Let's now apply this knowledge to solve the above Quiz. Give the output of the following code snippet in the comment section and let's see who can solve this problem.
/* Answer output of the following code in comment section */
const amazonOrder={
item:"2019 Apple MacBook Pro(16 GB RAM)",
cost:"2,15,490.00 Indian Rupees",
deliveryDate:"31 August 2021",
shippingAddress:'ABC'
}
const generateOrderMsg=function({item:product,cost:price,deliveryDate,shippingAddress,shippingCost="80 Indian Rupees"}){
return `Hello Sir/Madam,${product} will reach ${shippingAddress} on ${deliveryDate}. Cost is ${price} and addition shipping cost of ${shippingCost} `
}
console.log(generateOrderMsg(amazonOrder));
Congratulation 🥳on reaching the end of this article. If you have read both Part 1 and 2 of this Destructuring Series then you are now an expert😎 in this topic of JavaScript. If you still have any doubt🤔 then you can Dm me .
Thanks for reading.