Here I found the following piece of code:
hash = hash | 0; // Convert to 32bit integer
Could anyone explain why this code converts hash
to 32 bit integer?
Here I found the following piece of code:
hash = hash | 0; // Convert to 32bit integer
Could anyone explain why this code converts hash
to 32 bit integer?
The reason is that bitwise operators implicitly convert their arguments to 32-bit ints before applying the operator. Other than that, | 0
performs a bitwise OR with 0
, which is essentially a no-op.
In the ES6 spec, the |
operator is defined as a binary operator in 12.11, and then the runtime semantics are defined in 12.11.3.
In particular, steps 7 and 9 cast the arguments to 32-bit ints, and step 11 returns the result as a 32-bit int:
The production A : A @ B, where @ is one of the bitwise operators in the productions above, is evaluated as follows:
- Let lref be the result of evaluating A.
- Let lval be GetValue(lref).
- ReturnIfAbrupt(lval).
- Let rref be the result of evaluating B.
- Let rval be GetValue(rref).
- ReturnIfAbrupt(rval).
- Let lnum be ToInt32(lval).
- ReturnIfAbrupt(lnum).
- Let rnum be ToInt32(rval).
- ReturnIfAbrupt(rnum).
- Return the result of applying the bitwise operator @ to lnum and rnum. The result is a signed 32 bit integer.
[emphasis added]
It is because |
is an bitwise operator. SO
hash = hash | 0;
performs the bitwise or
operation, i.e bitwise or
of hash and zero.
You will observe similar behaviour for other bitwise operators too, for example :
var x = 4;
console.log(4 >> 1); // right shift bitwise operator
Thanks to @Keith to mention that" Bitwize operation in JS, are only 32bit signed int's." in comment.