0

I know about boolean logic. However, this question pertains to a specific use case of JS. A & is used with the same variable on both sides.

In the code snippet below, what is the reason for hash = hash & hash?

const hash =(string) => {
  //set variable hash as 0
  var hash = 0;
  // if the length of the string is 0, return 0
  if (string.length === 0) return hash;
  for (i = 0 ;i<string.length ; i++)
  {
    ch = string.charCodeAt(i);
    hash = ((hash << 5) - hash) + ch;
    hash = hash & hash;
  }
  return hash;
 };
John Difool
  • 5,572
  • 5
  • 45
  • 80
  • Also, here's a CodeSandbox app for visualizing bitwise operations: https://7io9he.csb.app/ – jsejcksn Sep 17 '22 at 12:51
  • 1
    "What is the purpose of & a value to itself?" the same as `|0` or `>>0`. It (ab)uses a side-effect of bit-operations in JS – Thomas Sep 17 '22 at 12:52
  • 1
    @Thomas if you don't know a dupe, you should post an answer explaining that side-effect for those who aren't aware of it – Nick Sep 17 '22 at 13:00
  • All these operations seem to result in no op. What is the side-effect? – John Difool Sep 17 '22 at 22:16

0 Answers0