title: How to check for falsy values in properties of a chain of connected objects?
body: <p>I'm using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR" rel="nofollow noreferrer">Logical OR (||) operator</a> to check and assign values if they are not falsy in the following way:</p>
  <pre><code>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';
  </code></pre>
  <p>But when <code>result</code>, <code>result.results</code>, <code>result.results[0]</code> or <code>address_components</code> is undefined, I get the following error:</p>
  <pre><code>Uncaught TypeError: Cannot read property [name_of_property] of undefined
  </code></pre>
  <p>I tried fixing this using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="nofollow noreferrer">Optional chaining (?.) operator</a> to access properties, as below:</p>
  <pre><code>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';
  </code></pre>
  <p>But it still fails without getting to assigning the default value 'unknown district'.</p>
  <p>I could get the code to work by using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator" rel="nofollow noreferrer">Conditional (ternary) operator</a> and checking for falsy values as below:</p>
  <pre><code>let locationDistrict =
                      (result &amp;&amp; result.results &amp;&amp; result.results[0] &amp;&amp; result.results[0].address_components[2]) ? result.results[0].address_components[2].long_name :
                      (result &amp;&amp; result.results &amp;&amp; result.results[0] &amp;&amp; result.results[0].address_components[1]) ? result.results[0].address_components[1].long_name :
                      (result &amp;&amp; result.results &amp;&amp; result.results[0] &amp;&amp; result.results[0].address_components[0]) ? result.results[0].address_components[0].long_name :
                      'unknown district';
  </code></pre>
  <p>But I'm sure there's a better and more legant way to do this.</p>
  <p>Why isn't the <code>||</code> operator picking up the 'undefined' value of the expression when either of it's chained objects is undefined? How should I use the <code>||</code> operator  to check for falsy values when the left-hand side operand contains deeply located properties within a chain of connected objects?</p>