let { prop1 , prop2 } = object
If you want to know about array destructuring you can have look at it here
So Object destructuring is a method where properties of an object are assigned to a variable
Before ES6, we use to do that like this
let obj = {
firstname : "f_name",
lastname : "l_name"
}var first_name = obj.firstname;
var last_name = obj.lastnameconsole.log(first_name)
console.log(last_name)
but after the introduction of destructuring in ES6, we can do this even more easily
let obj = {
firstname : "f_name",
lastname : "l_name"
}let { firstname:first_name , lastname:last_name} = objconsole.log(first_name)
console.log(last_name)
So less code, but here is a catch always while doing so you need to keep in mind that you always refer to the same property name used in your object while destructuring else compiler will throw an error and the variables name should be mentioned after the colon
here we can have the same variable name as the one with the property name of an object, by doing so we have lesser variable declarations in the scope
let obj = {
firstname : "f_name",
lastname : "l_name"
}let { firstname , lastname} = objconsole.log(firstname)
console.log(lastname)
Now what if we have a nested Object, no worries let it is also the same let's take an example for the same
let obj = {
firstname : "f_name",
lastname : "l_name",
education :{
degree:"bachelors"
}
}const {education:{degree:deg}} = obj /* here deg is variable and degree is property name we can eliminate the useage of variables const {education:{degree}} = objconsole.log(degree)*/console.log(deg)/*OUTPUT : bachelors*/
Now what if the nested object is missing
in such a case we get an error
TypeError: cannot read property ‘ propname ’ of undefined
so this can be overcome by giving the default value
Syntax = let { property_name : { property_name } = default_value } = object
let _obj = {
firstname : "f_name",
lastname : "l_name",
}const {education:{degree} = {}} = _objconsole.log(degree)/*OUTPUT : undefined*/
by giving a default value we don't get any error