Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array at a time.
The right side of the statement contains the Javascript object that we want to split into variables; the left side contains a “pattern” for the corresponding properties of the object. This “pattern” is usually a list of variable names.
Here’s how to destructure values from an object:
var employee = { // Object we want to destructurefirstname: 'Jon',lastname: 'Snow',dateofbirth: '1990'};// Destructuring the object into our variablesvar { firstname, lastname, dateofbirth } = employee;console.log( firstname, lastname, dateofbirth);
The following code destructures the object into variables with a different name than the object property:
var employee = { // Object we want to destructurefirstname: 'Jon',lastname: 'Snow',dateofbirth: '1990'};// Destructuring the object into variables with// different names than the object variablesvar { firstname: fn, lastname: ln, dateofbirth: dob } = employee;console.log( fn, ln, dob);
We can also assign default values to variables whose keys may not exist in the object we want to destructure. This will prevent our variable from having an undefined value assigned to it. The code below demonstrates this:
var employee = { // Object we want to destructurefirstname: 'Jon',lastname: 'Snow',dateofbirth: '1990'};// Destructuring the object into variables without// assigning default valuesvar { firstname, lastname, country } = employee;console.log("Without setting default values")console.log( firstname, lastname, country);// Destructuring the object into variables by// assigning default valuesvar { firstname = 'default firstname',lastname = 'default lastname',country = 'default country' } = employee;console.log("\n After setting default values")console.log( firstname, lastname, country);
It allows us to write code that is shorter and more readable, since it allows us to bundle variables inside one object and then access the individual elements in another function without using the dot notation.
Since it allows us to set default values for specific variables, it makes sure the code doesn't break in case a value is missing.
Since we can assign aliases for different variables, it allows the code to be shorter and more robust while ensuring readability and descriptive variable names.
When using large frameworks that pass objects to functions which a lot of values, if we only need one or two values, we can destructure it. This helps make the code easier to work with.
Using object destructuring in JavaScript has some cons too which are listed below:
If an object has a lot of variables, it becomes very tedious to destructure it. In this case, use the dot notation.
In case an object is different from what was expected and we don't account for that, it might result in bugs in the code.