title: How to sort an array with null values
body: <p>There are quite a few question related to the topic, but I couldn't find the right solution for my case.</p>
  
  <pre><code>var arr = [a, b, null, d, null]
  </code></pre>
  
  <p>and am sorting this Array with below logic</p>
  
  <pre><code>return function(a,b){ 
  
      if(a === null){
        return 1;
      }
      else if(b === null){
        return -1;
      }
      else if(a === b){
        return 0;
      }
      else if(ascending) {
        return a &lt; b ? -1 : 1;
      }
      else if(!ascending) {
        return a &lt; b ? 1 : -1;
      }
    };
  </code></pre>
  
  <p>I get the following outputs for </p>
  
  <pre><code>Ascending : [a, b,  d, null,null]
  
  Descending : [d, b,  a, null,null]
  
  Expected : [null, null,d, b,  a]
  </code></pre>
  
  <p>What am I doing wrong?</p>