I am currently utilizing the Logical OR (||) operator to verify and assign values if they are not falsy in the following manner:
let locationDistrict =
result.results[0].address_components[2].long_name ||
result.results[0].address_components[1].long_name ||
result.results[0].address_components[0].long_name ||
'unknown district';
However, I encounter an error when result
, result.results
, result.results[0]
, or address_components
is undefined:
Uncaught TypeError: Cannot read property [name_of_property] of undefined
To address this issue, I attempted using the Optional chaining (?) operator to access properties, as shown below:
let locationDistrict =
result?.results[0]?.address_components[2]?.long_name ||
result?.results[0]?.address_components[1]?.long_name ||
result?.results[0]?.address_components[0]?.long_name ||
'unknown district';
Unfortunately, it still fails to assign the default value 'unknown district'.
I managed to make the code functional by employing the Conditional (ternary) operator and checking for falsy values like so:
let locationDistrict =
(result && result.results && result.results[0] && result.results[0].address_components[2]) ? result.results[0].address_components[2].long_name :
(result && result.results && result.results[0] && result.results[0].address_components[1]) ? result.results[0].address_components[1].long_name :
(result && result.results && result.results[0] && result.results[0].address_components[0]) ? result.results[0].address_components[0].long_name :
'unknown district';
Nevertheless, I believe there must be a more elegant solution available. Why does the || operator not detect the 'undefined' value of the expression when any of its chained objects is undefined? How can I utilize the || operator effectively to check for falsy values within deeply nested properties of interconnected objects on the left-hand side operand?