DEV Community

Deepa Chaurasia
Deepa Chaurasia

Posted on • Updated on

Destructuring in Javascript

Destructutring is act of unpacking elements in an array or object.It not only allows us to unpack but also manipulate and switch elements when you demand.

Destructuring in Arrays

Javascript allows you to use rest operator with destructing array to assign the rest of regular array to variable.

Example of Destructing in Array

Image description

As you have noticed ['devesh','ram'] remaining both get strored in var3.

We use ',' to skip variables at destructing array's first and second positions ,you just leave it blank.

Like this:
Image description

How default value get assign in Destructing

Let's see
Image description

Here you'll notice 'deepa' and 'chaurasia' are default value of 'firstName' and 'lastName' respectively

*Therefore when we have tried to extract first index element it gave 'chaurasia' as output, because only zeroth index value exists in ["Deepa Chauraisa"]. It contains only one element . *

Object Destructing in Javascript

Object destructing is unique technique that allows you to neatly extract an object's value to new variables.

Let's see with Example

Image description

here key 'firstName' i am talking about in the object on left side.

So your key will be your object's key whose value you want to assign in your new variable (i.e your value here)

Here is the another example of same:

Image description

This was pretty much all about destructing.

Thanks for reading,Hope it helped
Please like,save and comment :)

Top comments (0)