JS/TS optional chaining operator
I'm making this post simply so that I can refer back to it every single time that I want to make reference to the use of this operator in code, and can NOT for the life of me remember what its actually called. I feel like I have some kind of mental block around it for some reason, but I always seem to forget what its called.
The optional chaining operator is what I have otherwise referred to as "the question mark operator" when I couldn't remember what it was called. Per the MDN documentation this is what it does:
If the object accessed or function called using this operator is
undefinedornull, the expression short circuits and evaluates toundefinedinstead of throwing an error.
That last part that I highlighted is where the real value here is, that's the big win with this operator. Here's the MDN accompanying code sample for example:
const adventurer = {
name: "Alice",
cat: {
name: "Dinah",
},
};
const dogName = adventurer.dog?.name;
console.log(dogName);
// Expected output: undefined
console.log(adventurer.someNonExistentMethod?.());
// Expected output: undefined