JavaScript ES6 Destructuring in Depth

Destructuring is alluring language feature, I’ve been using the most. Destructuring is provides a convenient way of extracting multiple values from the objects, Arrays, Map and Set.

For better and easy understanding, let me create a js object called person.

Ancient times we used to do like, below shown, to read data from objects and arrays.

Now, you can do like show below with Object destructuring

pull deeply nested data

You can also pull properties as deep as you want, like shown below

Renaming Destructure Variables

Sometime you may need to rename or alias variable names while destructure them for different reasons like default names may be odd, maybe you do not like that variable names or you want to give name based on current context or it’s already taken in your scope. Whatever the reason is renaming values is effortless.

In the below example, I am renaming first_name and last_name to FirstName and LastName.

assign default values

By default, properties that aren’t found will be undefined, just like when accessing properties on an object with the dot or bracket notation. However if you are trying to access a deeply nested property of a parent that doesn’t exist, then you’ll get an exception.

You can set defaults or fallback values with destructuring so that if an item or key is not in that object it will fall back to what you have set at the default.

One thing you have to remember is “undefined, null, false and 0 are all still values” which means if the object contains mentioned items as values(Ex: first_name: undefined),destructuring will not take default or fallback value.

While assigning default you can also rename the default variable names as shown below, syntax is little vague.

All the above mentioned is applies to Arrays, Map, set and Functions. One more use case you can swap variables without creating temp variables with Destructure.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments Protection Status
Would love your thoughts, please comment.x