The optional chain call is currently in phase 1, and all the information you need is in this repository.
What is it?
The optional chain call allows us to check if the object exists and then try to access its properties. There are similarities in some other languages. For example, c# has an empty conditional operator that behaves very similar to the proposed optional chain call.
Why do we need it?
Have you ever checked for the existence of an object or array before accessing its properties? If you forget, let me remind you something like this:
if(specimen && specimen.arms && specimen.arms.length > 2)
console.log("This is probably an alien");
Copy the code
The reason we do these checks is because javascript allows anonymous objects that don’t necessarily have the structure we’re accessing, so if we don’t check the parent item in the object tree, we might have a lot of errors like this:
Because at least specimen does exist in this error, but it doesn’t have the arms property, so we’re trying to get the length of undefined.
So, is there a better way?
We can use an optional chain call like this:
if(specimen? .arms? .length > 2) console.log("This is probably an alien");Copy the code
Remember here that the optional chain call uses what? Instead of? , which means it looks like this when used to access items in an array:
var firstArm = specimen? .arms? . [0]; Var secondArm = specimen? .arms? [1]. / / errorCopy the code
Similarly, when using it to check for the presence of a function:
var kickPromise = specimen? .kick? . (); Var punchPromise = specimen? .punch? (a); / / errorCopy the code
In this case, we check if kick exists before calling it as a function!
How does it work?
? The. Operator checks what is on the left, null or undefined. If so, the expression shorted returns undefined. Otherwise, the expression continues to evaluate as if there were no errors.
When can I use it?
Well, it’s still a proposal, so it’s not in Vanilla JavaScript yet. However, it can be used with Babel!
To keep up with the proposals, as well as to have a deeper understanding and check out some examples, you should check them out on the GitHub repo if you like!
Thank you for reading