So, What is Destructuring?
why this concept is necessary?
Let’s remember the old fashion to retrieve elements in the array
From the above example, we can see that when we want to extract data from an array, we do the same thing again and again.
Lets us use the above example
Variables can also define before assignments like this
Look at the above codes, variables are set from left to right. So the first element in the array is assigned to the first variable and the second element in the array is assigned to the second variable and so on…
What if we want some selected indexes from an array and ignore the rest, We can skip the elements from an array, how? Look at the below code.
Look at the above code, if we want the first, third, and last elements from the array then we put an extra comma in between variables. The comma separator is used to skip values in an array. So if you want to skip an item in an array, just use a comma.
Now think about a big array, you want to assign some of its elements to some variable, and the rest elements store in another array. Here comes the concept of Rest and Spread operator
What are Rest operator and Spread operator?
spread operator OR as a
Rest operator collects all remaining elements into an array. The Rest variable must always be the last otherwise a
SyntaxError is thrown.
Spread operator allows iterables( arrays / objects / strings ) to be expanded into single elements.
Let’s understand by example.
Look at the above code, the first two elements from an array are assigned to a variable (a & b), and rest elements store in the array (c). Using this operator, you can unpack and assign the remaining part of an array to a variable.
If the (…) operator appears on the right-hand in destructuring then it is a
SPREAD SYNTAX.It takes all the other elements in the array which have no variable mapped to them and then maps it to the rest variable.
When you can have more variables on the left-hand side, it assigns the single elements in the array equal to the variables
Destructuring can also used for swapping variables