Reputation: 415
I am creating and answering this question for myself because googling "Javascript ?. Operator" provides no useful results.
Questions about the ?. operator to be answered:
Upvotes: 1
Views: 76
Reputation: 415
For example consider this Person Object
let person = {
name : {
first : "John",
last : "Doe"
},
age : 31
}
I would access this person's last name as
let lastName = person.name.last;
This is all grand but what if the name object didn't exist? Well the preceding line of code would throw the following error
Uncaught TypeError: Cannot read property 'last' of undefined
To solve this the name property must be checked to make sure it exists. This will turn our simple one liner into the following code
let lastName;
if(person.name){
lastName = person.name.last;
}
or
let lastName = person && person.name && person.name.last
The first option is just a hassle and the second option isn't swell either. (I personally think the syntax is confusing) For an explanation the second option is checking if person is truthy if it is, it will check if person.name is truthy, if it is person.name.last will be saved into lastName.
So here is the magic of the Null Propagation Operator I can rewrite all of the above snippets as
let lastName = person?.name?.last
Now if person or name is null/undefined lastName will be set to null/undefined and no error will be thrown. For highly nested objects this can save a lot of error checking and lines of code.
Typescript supports optional chaining as of 3.7 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining
Upvotes: 4