Optional Chaining allows us to check if an object exists before trying to access its properties. Some other languages have something similar. C#, for example, has a Null Conditional Operator that behaves very similarly as the proposed Optional Chaining.
Have you ever had to check for the existence of objects or arrays before accessing its properties? If you forget, it may look a little bit like this:
if(specimen && specimen.arms && specimen.arms.length > 2) console.log("This is probably an alien");
Because, at least in the case of the error,
specimen does exist, but it does not have an
arms property. Therefore, we tried to get
length of something that was
Instead of all that, we can chain optional checks like this:
if(specimen?.arms?.length > 2) console.log("This is probably an alien");
However, keep in mind that the Optional Chaining operator is
? - this means that when using it to access an item in an array, it will look like this instead:
var firstArm = specimen?.arms?.; //CORRECT var secondArm = specimen?.arms?; //WRONG
Similarly, when using it to check for the existence of functions:
var kickPromise = specimen?.kick?.(); //CORRECT var punchPromise = specimen?.punch?(); //WRONG
In this case, we check if
kick exists before calling it as a function!
The operator checks if whatever is to the Left-Hand Side of
undefined. If it is, then the expression short-circuits and returns
undefined. Otherwise, the expression continues to evaluate as if nothing is wrong.
To stay up to date with the status of the proposal, as well as to have a more in-depth understanding and to check some examples, you should check their GitHub repo! You can also find the specs here, but I won't get into that since most of that document goes way over my head 😅
You're welcome! ❤️