title: Optional Chaining in JavaScript
body: <p>I've been programming a lot in Swift recently. Today I did some work in JavaScipt when question popped up to me:</p>
  
  <p>Is there something similar to optional chaining in JavaScript? A way to prevent <code>undefined is not an object</code> without any variables?</p>
  
  <p>Example:</p>
  
  <pre><code>function test(){
     if(new Date() % 2){
        return {value: function(){/*code*/}};
     }
  } 
  
  test().value();
  </code></pre>
  
  <p>will fail half of time because sometimes <code>test</code> returns undefined. </p>
  
  <p>The only solution I can think of is a function:</p>
  
  <pre><code>function oc(object, key){
     if(object){
        return object[key]();
     }
  }
  
  oc(test(), 'value');
  </code></pre>
  
  <p>I would like to be able to do something like:</p>
  
  <pre><code>test()?.value()
  </code></pre>
  
  <p>The part after the question mark is only executed if <code>test</code> returned an object.</p>
  
  <p>But this is not very elegeant. Is there something better? A magic combination of operators? </p>
  
  <p><strong>Edit</strong> I know I could rewrite <code>test</code> to return something. But I'm wondering if there's something like optional chaining. I'm not interested in a particular solution to the above <em>example</em>. Something that I also can use if have no control over the function returning undefined.</p>