Destructuring is a way to unpack elements from an array or object or characters from a string. It is used to extract the values from arrays or objects and assign them to variables.
On the left-hand side, we specify the variable names, and on the right side the array or object from which values need to be extracted.
Destructuring Arrays :
// Destructuring an array of elements in the variables a, b, c let [a, b, c] = [1, 2, 3]; console.log(a) // 1 console.log(b) // 2 console.log(c) // 3
Destructuring Strings :
// Destructuring Strings characters into the variables a, b, and c let [a, b, c] = "hey"; console.log(a); // h console.log(b); // e console.log(c); // y
Destructuring Objects :
// Destructuring an object properties in the variables firstname, lastname let {firstname, lastname} = { firstname: 'John', lastname: 'Jay' }; console.log(firstname) // John console.log(lastname) // Jay
The property names must match with the variable name otherwise it’s not going to extract the value and gives undefined.
// Destructuring an object properties in the variables firstname, lastname let {fname, lastname} = { firstname: 'John', lastname: 'Jay' }; console.log(fname) // undefined console.log(lastname) // Jay
Let’s take an example of an object having nested objects :
let {name, address: {city}} = { name: 'Jay', age: 23, address: {city: 'Raipur' }}; console.log(name) // Jay console.log(city) // Raipur
Setting default values :
We can set the default values for the variables that get assigned to the variable if the corresponding key does not exist in the key.
let {firstname = 'Jetty', lastname} = { lastname: 'Jay' }; console.log(firstname) // Jetty console.log(lastname) // Jay
Aliases with Destructuring :
There are cases where you want the variable to have a different name than the property name; in this case make use of a colon ( : ) to specify the alias name after the property name.
// Extracting firstname as name let {firstname : name, age} = { firstname: 'John', age: 23 }; console.log(name) // John console.log(age) // 23
Subscribe to our Youtube channel for more videos :