Reputation: 403
What I'm trying to do at the beginning of my function is easy to see from my comment
this.move = function ( )
{
if (this.dx | this.dy != 0) return; // exit early if both this.dx and this.dy are zero
That is, I want the equivalent of if (this.dx == 0 && this.dy == 0)
. I thought the bitwise OR
is correct because this.dx | this.dy
is not equal to zero
if and only if this.dx
has at least one bit on or this.dy
has at least one bit on (or both have at least one bit on). But I must be wrong, because my test
this.move = function ( )
{
console.log("this.dx = " + this.dx + ", this.dy = " + this.dy); // TEST
if (this.dx | this.dy != 0) return; // exit early if both this.dx and this.dy are zero
is showing that the rest of the function is executing when this.dx
and this.dy
are both zero.
What's going on here?
Upvotes: 1
Views: 40
Reputation: 34288
According to the precedence table The bitwise OR will be executed after the inequality check is done. For example:
[JS]> 0 | 0 == 0
1
Hence, your expression actually is executed as:
if (this.dx | (this.dy != 0)) { ... }
To fix the issue, parenthesize the bitwise OR: if ((this.dx | this.dy) != 0)
.
Also, as @Jon-Skeet pointed out, the correct check probably should be with an ==
.
Upvotes: 1
Reputation:
Problem is the condition is executed as:
this.dx | (this.dy != 0)
Try this:
if (!(this.dx | this.dy)) return;
Upvotes: 3