Hi and welcome to the world of JavaScript where we make coding easy and fun.
Today we're going to talk about destructuring
that is a feature that makes working with arrays and objects a lot simpler.
Destructuring is a way of extracting data
from arrays, objects, maps and sets into distinct variables.
It helps us avoid repetitive and confusing code by allowing us to extract data
from complex data structures in a concise and organized manner.
For example, let's consider the following code where we are going to have an object
of a person and person's name is going to be Nata,
their age is going to be 26 and their occupation is going to be a developer.
And let's consider what would happen if we want to have these in separate variables.
We would probably do something like this.
The name would be person name
and the age would be person age and the
occupation would be person occupation.
As you can see, this code is repetitive
and can become confusing if we have multiple properties to extract.
This is where Destructuring comes in handy.
The same code but with Destructuring would be this.
So let's comment these out, create a constant and just do name,
age and occupation and let's assign it to a person.
Now, if we were to console log this,
we would see that this variable directly hold the value of the object properties
presented in the person, not at 26 and developer,
let's also consider how Destructuring arrays would work.
Let's create an array of numbers and let's do 12345.
If we wanted to have variables for 1st,
second and third elements here, we would have to do something like this.
And this code is also very repetitive and it can get complex if we have multiple
items that we want to pull out of the array.
But same can be achieved with something like this.
Constant, 1st, second and third.
And let's assign it to numbers.
And now let's console log the values.
Let's run this and we're going to see one, two, three appear from our numbers array.
So you could do something same with the person object and pair it
with Destructuring concept and also the spread operator that we talked about.
So let's say that you want to get all
of the information from the person object except for occupation.
So let's comment this out so that we don't have conflicts with the variable names
and let's say we create a const and it's going to have
occupation and then rest of the items from the person.
So let's console log rest and you're going to see that we're going
to have an object created for the rest and it does not contain the patient.
So in conclusion, Destructuring is a powerful feature
in JavaScript that makes working with arrays and objects much easier.
It helps us extract data in a concise and organized manner,
making our code cleaner, more readable and less prone to errors.
That's all for today.
Thanks for watching and see you in the next video.