title: Why 5 bit left shift in hashing function?
body: <p>A popular answer for generating a hashing function in JS is given in <a href="https://stackoverflow.com/questions/6122571/simple-non-secure-hash-function-for-javascript">Simple (non-secure) hash function for JavaScript?</a> and <a href="https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript">Generate a Hash from string in Javascript</a></p>
  
  <p>One example of the code is:</p>
  
  <pre><code>String.prototype.hashCode = function() {
      var hash = 0;
      if (this.length == 0) {
          return hash;
      }
      for (var i = 0; i &lt; this.length; i++) {
          var char = this.charCodeAt(i);
          hash = ((hash&lt;&lt;5)-hash)+char;
          hash = hash &amp; hash; // Convert to 32bit integer
      }
      return hash;
  }
  </code></pre>
  
  <p>One line that doesn't make sense to me is <code>hash = ((hash&lt;&lt;5)-hash)+char;</code></p>
  
  <p>Could someone please explain WHY this is done? I gather that we are doing a <code>5 bit left shift</code> on the hash. Is there any reason why it is 5 bits and not 4 or 6? Also why do we then minus the hash and add the char? </p>