DEV Community

Mrityunjay-Palled
Mrityunjay-Palled

Posted on

Array and Object Destructuring in JavaScript

Array Destructuring: It is a process of extracting array element into different individual variables. For example, only eating your favorite part of the cake. Let's see how array elements can be destructured.

Image description

In the above example we can see that we are only interested with 1 and 2 so we destructured them into a variables called "one" and "two". Now let's see how we can get only 3 and 4

Image description

In the above example we can see that we added two commas to skip the values 1 and 2 coming from the Arr. And we stored the values 3 and 4 into a variable "three" and "four" respectively. We can use comma to skip the respective values while destructuring.

Let's see how array destructuring can be used to swap two variables without using the third variable

Image description

Object Destructuring: It is a process of extracting required property values from the object

Image description

In the above example we can see that we are only extracting "id"
and "company" from the given object

Image description

As we can see above, we are renaming "id" to "myId" and "company" to "myCompany" by using a colon in between. We can follow this method to rename property names to avoid name collisions

Top comments (2)

Collapse
 
saimwebhr profile image
Muhammad Saim Hashmi

Informative

Collapse
 
mrityunjaypalled profile image
Mrityunjay-Palled

Thak you