Repeatedly OR it with an empty object
When working on HTML that references properties/subproperties which may or may not exist, I find it essential to utilize safe navigation techniques.
A common challenge is accessing nested object properties like this.myForm?.name?.first_name
.
The debate around the need for safe navigation in ES arises from different perspectives, but until an official Elvis operator is introduced in JS, my workaround involves using double parentheses as follows:
(((this.myForm || {}).name || {}).first_name )
This method ensures that any potential undefined values are treated as empty objects, preventing errors and allowing smooth property extraction.
Although this approach may seem cumbersome in cases of multiple tiers, it provides a cleaner alternative to chaining &&
operators.
For array access, OR it with an empty array
In scenarios involving arrays, such as selecting the first element from a list of names, a similar approach can be applied:
((((this.myForm || {}).names || [])[0] || {}).first_name )
Handling edge cases
Dealing with situations where elements in the chain are 0 or "" requires cautious handling. By incorporating the double parentheses technique, unexpected values like 0 or "" are managed effectively without triggering errors.
Example
The examples provided demonstrate the functionality of the workaround in different scenarios, showcasing its reliability in handling potentially missing or erroneous data.