Optional Chaining is a feature implemented in Latest javascript.
Let’s see what is the problem solve with this feature.
For example, An object contains following properties.
let employee = {
"id":1,
"name":"abc"
"role" : {
"id": 1,
"name":"Admin"
}
}
An object contains plain properties as well as sub childs(roles). Let’s find the role id for an employee.
let roleId = employee.role.id
console.log(roleId) // Prints 1
The above code works and prints role id if employee, and role objects are not null.
If employee or role object is null, Then It throws Uncaught TypeError: Cannot read property 'id' of
and returns undefined
.
To avoid error, manually check each object exists using if or conditional ternary operator
Following is one way using conditional operator using if condition
if (employee && employee.role & employee.role.id){
console.log(employee.role.id)// prints 1
}
Another way to handle Cannot read property
errors, use optional chaining property in ES11.
What is Optional Chaining operator?
What ES version supports optional chaining?
Es11 or EcmaScript 2020 supports Optional Chaining operator.