Property chaining challenges:
Working with JSON structure involves a lot of conditional checks, accessing nested properties of JSON, and checking multiple And operators (&&) to verify whether the given value exists or not. If it does exists then retrieve the value of that attribute.
While accessing or mapping an object’s properties we came across this error:
TypeError: Cannot read property ‘********’ of undefined.
The cool thing about this operator is that the second expression is never executed if the first expression is false. This has some practical applications, for example, to check if an object is defined before using it we can first check if an object exists, and then try to get one of its properties:
Even if a car is null, we don’t get errors and the colour is assigned a null value.
We can go down multiple levels:
Obj can have a different set of properties during runtime:
Thus we have to manually check the property’s existence:
That’s a lot of overlapping code.
Optional chaining, as a part of ES2020, changes the way properties are accessed from deep objects structures.
What is Optional Chaining?
Optional chaining allows us to check if an object exists before trying to access its properties. In simple words, we need not validate for null or undefined while accessing each property on the hierarchy.
“?.” is used as the optional chaining operator.
Let’s see how we can handle multiple ways of accessing the properties of an object:
We can soon rewrite the above line as:
The basic rule is if any of the values after ‘a?’ are null or undefined, then the statement will return null or undefined without throwing an error.
An alternative for not repeatedly adding the ‘?’ operator at every level provided we are confident that every user has an address but uncertain if the user exists is:
We need to check the existence of objects or arrays prior to accessing its properties and if while iterating over an array too.
If the data variable is null or undefined?
We would get an error - type error: cannot read property ‘data’ of undefined.
The solution to this is to check whether our data exists and isn’t empty, this can be determined by checking the array.length.
We can improve the code with a simple question mark.
Let's take another example:
In order to access the values of this object (the object can be undefined or null)
Using optional chaining we can:
Using optional chaining with function calls causes the expression to automatically return ‘undefined’ instead of throwing an exception if the method is not found:
Optional chaining brings a lot of benefits, by reducing the complexity and making the code readable.