Contents
What is destructuring assignment?
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
- MDN
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.
Use Cases
- 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 foo
property. bar
property is destructured and renamed as newBar
.
The same can be used to extract values from parameters into standalone variables
|
|
Create a shallow copy of objects
Using ... 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.
|
|
Swap values
Variables can be swapped without need for a temp variable
|
|
Subset of a object’s properties
Using destructuring assignment and ‘,’ operator
|
|
Using Object Destructuring and Property Shorthand
|
|
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.
Conclusion
ES6 introduced one of the most awaited JavaScript features: destructuring. It helps to write more cleaner and readable code. I hope you enjoyed reading this and find this helpful. I sincerely request for your feedback. You can follow me on twitter @lifeClicks25.