ES6 Object Destructuring
ES6 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).
Output
100
200
Output
Arun
First
24
Example
1. const {x = 100, y = 200} = {x: 500};
2.
3. console.log(x); // 500
4. console.log(y); // 200
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
Example
1. const num = {x: 100, y: 200};
2. const {x: new1, y: new2} = num;
3.
4. console.log(new1); //100
5. console.log(new2); //200
In the above example, we have assigned the property name as x and y to a local
variable, new1, and new2.
Output
100
200
Example
1. let name, division;
2. ({name, division} = {name: 'Anil', division: 'First'});
3. console.log(name); // Anil
4. console.log(division); // First
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
Example
1. let {a, b, ...args} = {a: 100, b: 200, c: 300, d: 400, e: 500}
2. console.log(a);
3. console.log(b);
4. console.log(args);
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
1. const {a:num1=100, b:num2=200} = {a:300};
2. console.log(num1); //300
3. console.log(num2); //200
Output
300
200