title: Combined Comparison / "Spaceship" Operator (<=>) in Javascript?
body: <p>Ruby has something called a Combined Comparison or "Spaceship" Operator, it looks like this: <code>&lt;=&gt;</code></p>
  
  <p>It does the following:</p>
  
  <pre><code>a &lt;=&gt; b :=
      if a &lt; b then return -1
      if a = b then return  0
      if a &gt; b then return  1
  </code></pre>
  
  <p><a href="https://stackoverflow.com/a/827656/5620297">Credit</a></p>
  
  <p>Is there a similar Operator in Javascript? If not, how can I end up with the same result?</p>
  
  <hr>
  
  <p><strong>@madox2</strong> suggested using <code>Math.sign(a - b)</code>, which works for number, but not arrays (to compare arrays you need to use <code>array.length</code>).</p>
  
  <p>It also does not work in Internet Explorer, Safari or all Mobile Browsers (see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign#Browser_compatibility" rel="noreferrer">MDN</a>)</p>
  
  <hr>
  
  <p><strong>@duques_l</strong> found a function <a href="http://sabrelabs.com/post/48201437312/javascript-spaceship-operator" rel="noreferrer">here</a>. It works very well, you can test it on <a href="https://jsfiddle.net/8pvgfkq7/" rel="noreferrer">JSFiddle</a></p>
  
  <p>The only problem is if the strings are not comparable the function returns <code>-1</code> instead of <code>nil</code></p>
  
  <p>Update: <strong>@duques_l</strong> changed the function a bit and now it works fine (I think so anyway, here is the <a href="https://jsfiddle.net/8pvgfkq7/3/" rel="noreferrer">JSFiddle</a>):</p>
  
  <pre><code>function spaceship(val1, val2) {
      if ((val1 === null || val2 === null) || (typeof val1 != typeof val2)) {
          return null;
      }
      if (typeof val1 === 'string') {
          return (val1).localeCompare(val2);
      }
      else {
          if (val1 &gt; val2) { return 1 }
          else if (val1 &lt; val2) { return -1 }
          return 0;
      }
  }
  </code></pre>
  
  <hr>