Javatpoint Logo
Javatpoint Logo

Object destructuring

It is similar to array destructuring except that instead of values being pulled out of an array, the properties (or keys) and their corresponding values can be pulled out from an object.

When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.

In object destructuring, the values are extracted by the keys instead of position (or index).

First, try to understand the basic assignment in object destructuring by using the following example.

Example - Simple assignment

Output

100
200

Let us understand the basic object destructuring assignment.

Example - Basic Object destructuring assignment

Output

Arun
First
24

Object destructuring and default values

Like array destructuring, a default value can be assigned to the variable if the value unpacked from the object is undefined. It can be clear from the following example.

Example

In the above example, the variables x and y have default values 100 and 200. Then, the variable x is reassigned with a value of 500. But the variable y is not reassigned, so it retains its original value. So, instead of getting 100 and 200 in output, we will get 500 and 200.

Output

500
200

Assigning new variable names

We can assign a variable with a different name than the property of the object. You can see the illustration for the same as follows:

Example

In the above example, we have assigned the property name as x and y to a local variable, new1, and new2.

Output

100
200

Assignment without declaration

if the value of the variable is not assigned when you declare it, then you can assign its value during destructuring. You can see the illustration for the same as follows:

Example

In the above example, it is to be noted that the use of parentheses () around the assignment statement is mandatory when using variable destructuring assignment without a declaration. Otherwise, the syntax will be invalid.

Output

Anil
First

Object destructuring and rest operator

By using the rest operator (…) in object destructuring, we can put all the remaining keys of an object in a new object variable.

Let us try to understand it with an example.

Example

Output

100
200
{ c: 300, d: 400, e: 500 }

Assigning new variable names and providing default values simultaneously

A property that is unpacked from an object can be assigned to a variable with a different name. And the default value is assigned to it in case the unpacked value is undefined.

Example

Output

300
200

Next TopicES6 Map




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA