Suppose you have a person
object with TWO prperties:
let person = {
firstName: 'Devv',
lastName: 'Sakib'
}
Before ES6, when you want to assign the variables to the properties of the person
object, you typically do like this:
let firstName = person.firstName
let lastName = person.lastName
But but but, ES6 make it more easier! There are an alternative way to assign properties of an object. Let's see
let { firstName: fName, lastName: lName } = person
Here, firstName
and lastName
prop are assgined to fName
and lName
variables.
Syntax:
let {
property: variable,
property: variable
} = object
Notice that the property name is always on the left whether it is object literal or object destructuring syntax.
TO KNOW: If the variables have the same name as the properies of the object, you can make the code more concise as follows:
let { firstName, lastName } = person
console.log(firstName) // "Sakib"
console.log(lastName) // "Smith"
In this examples, we declared two variables firstName
and lastName
, and assigned the properties of the object to the variables in the same statement.
When you assign a property that does not exist to a variable using the object destructuring, the variable is set to undefined
.
Example:
let { firstName, lastName, middleName } = person
console.log(firstName) // "Sakib"
console.log(lastName) // "Smith"
console.log(middleName) // undefined
The middleName
property does not exist in the person
object, that's why middleName
is undefined
Default Values
You are able to assign a default value of the variable when the property of an object doesn't exist.
Example:
let person = {
firstName: 'Devv',
lastName: 'Sakib'
}
let {
firstName,
lastName,
middleName = ''
} = person
console.log(middleName) // ''
In this example, we assigned empty string to the middleName
variable when the person
object doesn't have the middleName
property.
However, when the person object has middleName
property, the assignment works as usual:
Example:
let person = {
firstName: 'Devv',
lastName: 'Sakib',
middleName: 'IDK'
}
let {
firstName,
lastName,
middleName = ''
} = person
console.log(middleName) // 'IDK'
Destructuring a null object
If you know, a function may return an object or null in some case.
const person = () => {
return null
}
let { fname } = person()
But you can't destructure an null object. The code will throw a TypeError
TypeError: Cannot destructure property 'fname' of 'person()' as it is null.
To solve this, you can use the OR
(||) operator to fallback the null
object t an empty object.
let { fname } = person() || {}
Now, fname will be undefined
There are so many destructuring, will write later. See yaa
Top comments (0)