title: JavaScript analog of java.lang.Optional?
body: <p>I'm looking for a client-side JavaScript library that would let me write code similar to what I can do in other languages using some flavour of Option type, for example <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html" rel="noreferrer">java.lang.Optional</a>.</p>
  
  <p>My target is to avoid <code>null</code>/<code>undefined</code> checks in client code and make API more explicit.</p>
  
  <p>Here is the API I want to be able to write:</p>
  
  <pre><code>var dictionary = {
      key1: 'value1',
      key2: 'value2'
  }
  
  function getValue(key){
      var value = dictionary[key];
      if(value !== null &amp;&amp; value !== undefined) 
           return Optional.of(value);
      else 
           return Optional.empty();
  }
  </code></pre>
  
  <p>And here is the client code:</p>
  
  <pre><code>var value = getValue('key3');
  if(value.isPresent())
       console.log('got a value: ' + value.get().toUpperCase());
  else
       console.log('no value found!');
  </code></pre>
  
  <p>Or sometimes:</p>
  
  <pre><code>var value = getValue('unknown key').orElse('default value');
  </code></pre>
  
  <p>If I call <code>get()</code> on <code>Optional.empty()</code> value, it should throw some kind of <code>Error</code>.
  If I call <code>Optional.of()</code> on <code>null</code> or <code>undefined</code>, it should throw as well.</p>