What is destructuring assignment?
In essence, it is a convenient way to extract value/values from data stored in (possibly nested) objects and arrays. This feature was introduced in the 6th Edition of the ECMAScript standard, ES6 for short. It makes code concise, more readable and helps to avoid repeated destructing expressions.
- Access object properties and array items
- Create a shallow copy of objects
- Swap values
- Subset of a object’s properties
- Get properties like length of array, function name, number of arguments etc.
Access object properties and array items
Array destructuring helps to access array items in a much shorter way. Also, if the no element is present at any index then default value can be assigned like
thirdColor in the given example.
Destructuring of objects is used more in general. In the above example,
foo is assigned default value as the
obj doesn’t contains the
bar property is destructured and renamed as
The same can be used to extract values from parameters into standalone variables
Create a shallow copy of objects
... rest operator and destructuring shallow copy of objects or array.
I find this very useful especially in case of objects to delete properties in an immutable way. e.g. returning a user object to an api call where sensitive information like password etc should not be returned.
Variables can be swapped without need for a temp variable
Subset of a object’s properties
I have found these two above so useful, easy and very neat way to create a new object having subset of other object. Similarly, its very easy to convert an array to an object.
Get properties like length of array, function name, number of arguments etc.
These are few very cool and helpful features of destructuring. I would highly recommend to read the chapter Destructuring in Exploring ES6 by Dr. Axel Rauschmayer.