-
Notifications
You must be signed in to change notification settings - Fork 0
31 Optional Chaining
Biswajit Sundara edited this page Aug 18, 2023
·
1 revision
Optional Chaining is really useful when we deal with nested json data and inconsistent tree structure.
Let's say the back end API is fetching user data as below.
- The address part is not mandatory so some users will have it and some user won't
- This data is getting rendered in our UI application
const user ={
name: "Alia",
address: {
city: "Mumbai"
}
}
- Let's say we are displaying the city using this
console.log(user.address.city) - It will print the city as 'Mumbai'
The problem comes when we receive data without address property
const user = {
name: "Ranbir"
}
- Our UI code evaluates `user.address.city'
- And will encounter error
can't read properties of undefined - This will terminate the execution of the entire code block
Basically we need a mechanism using which we can return the data if exists or 'undefined' instead of an error
- We can apply conditional checking using ternary operator or ifElse conditions
- E.g
console.log(user.address ? user.address.city : 'undefined'); - However these conditional checking are ineffective when we get a deep nested json structure.
- The best approach is to use
optional chaining
Optional chaining helps to access properties from deeply nested objects without checking that each reference in the chain is valid
- The optional operator is used
(?.) - If it evaluates the value as undefined, then it will stop there and won't continue further
- E.g when we use
user.address?.cityit will stop when user.address returns 'undefined'