title: Returning the value of deep properties if they exist
body: <p>I wrote this function to search for and return the value of deep properties in an object and would like to know if there is a way to use recursion or something similar to make the function do the same thing but with less code (and possibly to remove the limit of at most five properties deep that can be tested).</p>
  
  <p>The function will return a deep property value if it exists, otherwise returns undefined.</p>
  
  <pre><code>function getDeep(o, p2, p3, p4, p5) {
      if (p5 !== undefined) {
          if (o.hasOwnProperty(p2) &amp;&amp; o[p2].hasOwnProperty(p3) &amp;&amp; o[p2][p3].hasOwnProperty(p4) &amp;&amp; o[p2][p3][p4].hasOwnProperty(p5)) {
              return o[p2][p3][p4][p5];
          }
      } else if (p4 !== undefined) {
          if (o.hasOwnProperty(p2) &amp;&amp; o[p2].hasOwnProperty(p3) &amp;&amp; o[p2][p3].hasOwnProperty(p4)) {
              return o[p2][p3][p4];
          }
      } else if (p3 !== undefined) {
          if (o.hasOwnProperty(p2) &amp;&amp; o[p2].hasOwnProperty(p3)) {
              return o[p2][p3];
          }
      } else if (p2 !== undefined) {
          if (o.hasOwnProperty(p2)) {
              return o[p2];
          }
      } else if (o !== undefined) {
          return o;
      }
  }
  window.onload = function () {
      var obj = {a:{b:{c:1}}};
      window.console.log(getDeep(obj, 'a', 'b', 'c')); // returns 1;
      window.console.log(getDeep(obj, 'a', 'b', 'd')); // returns undefined;
  }
  </code></pre>