DEV Community

Cover image for Optional chaining (?.)
Syed Kamal
Syed Kamal

Posted on

Optional chaining (?.)

Optional chaining is something I know about it later this week and i found it a powerful feature to use when accessing object keys

let personalData = {
userId: 2223 ,
userDetail:{
    name :{
    userName :{
        fullName:{
            firstName:"John",
            lastName:"Bob",
            otherName: {
                nickName:"Jonn"
            }
        }
    },
    age: 24
    }
}
}

this is users object in user object some user have parents information and some don't but we have to access it to utilize the information by calling it through dot(.) notation,
we are calling fatherName

personalData.userDetail.fatherName 
//VM2126:1 Uncaught TypeError: Cannot read property 'fatherName' of undefined at <anonymous>:1:34

it throws back an error as father name is not present in the object its something not good practice to print the error on UI so we have to use this old way using the AND operator

personalData && personalData.userDetail 
&& personalData.userDetail.fatherName 
//undefined

now we are in a safe zone by using the AND operator now it returns undefined instead of an error,

here comes optional chaining to reduce syntax simply use (?.) and it returns undefined if the value not exist

personalData.userDetail.username?.fatherName

this is very needful when accessing nested object properties and makes us on the safe side from causing an error

Top comments (0)