Array and Object Destructuring in JavaScript
Mrityunjay-Palled
Posted on October 9, 2022
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.
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
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
Object Destructuring: It is a process of extracting required property values from the object
In the above example we can see that we are only extracting "id"
and "company" from the given object
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
Posted on October 9, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 20, 2024