JavaScript Destructuring
The destructuring assignment introduced in ES6 makes it easy to assign array values and object properties to distinct variables. For example,
Before ES6:
From ES6:
Note: The order of the name does not matter in object destructuring.
For example, you could write the above program as:
let { age, gender, name } = person;
console.log(name); // Sara
Note: When destructuring objects, you should use the same name for the variable as the corresponding object key.
For example,
let {name1, age, gender} = person;
console.log(name1); // undefined
If you want to assign different variable names for the object key, you can use:
Array Destructuring
You can also perform array destructuring in a similar way. For example,
Assign Default Values
You can assign the default values for variables while using destructuring. For example,
In the above program, arrValue has only one element. Hence,
- the x variable will be 10
- the y variable takes the default value 7
In object destructuring, you can pass default values in a similar way. For example,
Swapping Variables
In this example, two variables are swapped using the destructuring assignment syntax.
Skip Items
You can skip unwanted items in an array without assigning them to local variables. For example,
In the above program, the second element is omitted by using the comma separator ,.
Assign Remaining Elements to a Single Variable
You can assign the remaining elements of an array to a variable using the spread syntax .... For example,
Here, one is assigned to the x variable. And the rest of the array elements are assigned to y variable.
You can also assign the rest of the object properties to a single variable. For example,
Note: The variable with the spread syntax cannot have a trailing comma ,. You should use this rest element (variable with spread syntax) as the last variable.
For example,
Nested Destructuring Assignment
You can perform nested destructuring for array elements. For example,
Here, the variable y and z are assigned nested elements two and three.
In order to execute the nested destructuring assignment, you have to enclose the variables in an array structure (by enclosing inside []).
You can also perform nested destructuring for object properties. For example,
In order to execute the nested destructuring assignment for objects, you have to enclose the variables in an object structure (by enclosing inside {}).
Note: Destructuring assignment feature was introduced in ES6. Some browsers may not support the use of the destructuring assignment. Visit Javascript Destructuring support to learn more.