Sign in

Object Destructuring in JavaScript

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"
}

but after the introduction of destructuring in ES6, we can do this even more easily

let obj = {
firstname : "f_name",
lastname : "l_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"
}

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"
}
}

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",
}

by giving a default value we don't get any error