Last updated on April 8, 2017
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
.
const person = { first_name: 'Arjun', last_name: 'PHP', address: { country: 'India', city: 'Hyderabad', } };
Ancient times we used to do like, below shown, to read data from objects and arrays.
const first_name = person.first_name; const last_name = person.last_name; console.log(first_name, last_name);
Now, you can do like show below with Object destructuring
const { first_name, last_name} = person; console.log(first_name, last_name);
pull deeply nested data
You can also pull properties as deep as you want, like shown below
//we can pull deeply nested data like this const { country, city} = person.address; //Old way of pulling deeply nested data const country = person.address.country; const city = person.address.city;
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.
// alias destructure Variables in ES6 const { first_name: FirstName, last_name:LastName} = person;
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.
// assign default values const { first_name = 'Pravinh', last_name, srue_name= 'A'} = person;
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.
// defalut value with rename const { first_name: FirstName = 'Pravinh', last_name: LastName, sure_name: Surename = 'A'} = person;
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.