How does 5.5 | 0 === 5
work?
Is | 0
in this context the bitwise OR
I suspect it to be? If so, why does it cut off everything after the point?
How does 5.5 | 0 === 5
work?
Is | 0
in this context the bitwise OR
I suspect it to be? If so, why does it cut off everything after the point?
Bitwise operators always coerce operands to 32-bit integers.
The operation is interpreted as
5.5 | (0 === 5)
which is
5.5 | false
which is coerced to
5.5 | 0
Now the 5.5
is converted to a 32-bit integer, so we have
5 | 0
which is 5
.
The relational operators bind more tightly than the bitwise operators which can be confusing. If you want to compare the result of a bitwise operator (unlike, say, an addition or multiplication), you have to parenthesize explicitly.
The |
performs operator is a bitwise OR operation, implicitly converting each operand to an 32-bit integer. As Pointy notes, 5.5 | 0 === 5
is parsed as 5.5 | (0 === 5)
, which evaluates to 5.5 | false
.
According to the specification:
…
5. Let lnum be ToInt32(lval).
6. Let rnum be ToInt32(rval).
7. Return the result of applying the bitwise operator @ to lnum and rnum. The result is a signed 32 bit integer.
And since X | 0
→ X
for any integer, it is effectivly just removing any fractional part of the number.
It doesn't equal true, it just doesn't equal false.
5.5 | 0 === 5
returns
5