Destructuring is a great way to unpack arrays and objects in Javascript. After unpacking you can assign to variables, create copies and do more in less lines of code.
Array Destructuring
Assigning to variables
In order to de-structure array, on the left side we put variables to be declared inside []
and the array to de-structure on the right side of equal sign. Now str1
has value of arr1[0]
, str2
has arr[1]
and can go on.
With functions returning arrays
We can also use the same method of assigning to variables above to catch the function returns and assign to variables.
Concatenating Arrays
Just put the arrays like ...arr1
(3 dots spread operator) inside square braces []
in any order you want and the result is combined array.
Object Destructuring
Similar to array destructuring we can unpack the objects using {}
curly braces. We used a similar approach in my last post where I wrote about the builder pattern and passing object inside constructor to initialize instance.
Assigning to variables
For assigning object properties to variables we pass in the keys inside the {}
which then creates them as variables. For example we created name variable. We can then also assign those key to custom variable name by doing this:
Creating a new Object by combining objects
For example we wanted to create a new from the existing User1 but with keys of User2. We can use spread operator (...)
inside {}
just like:
So in the new object the User1’s city,phone,university gets overwritten with User2’s keys and our new User3 becomes sherlock as well!.
Passing in as functional parameters
Rather than passing in list of parameters in a specific sequence or a full big object we can just setup our function to accept only specific keys:
So even though we passed in full object User1 and User3 the function only picked up name and city.