Bitwise OR definition is
returns a zero in each bit position for which the corresponding bits of both operands are zero
So it returns a one otherwise. Basically this means that 1 | 0
is 1
.
Behaves much like ||
, which returns true if one side is true.
However, we know that ||
, in case left side expression is true, stops at that and won't evaluate right side expression, because no matter what, the result will be true.
This means that
var a = 0, b = 0;
function incrementAAndReturnTrue(){
a++;
return true;
}
function incrementBAndReturnFalse(){
b++;
return false;
}
incrementAAndReturnTrue() || incrementBAndReturnFalse();
console.log(a); // 1
console.log(b); // 0
However, for bitwise OR operator, both sides are evaluated, no matter what.
var a = 0, b = 0;
function incrementAAndReturnOne(){
a++;
return 1;
}
function incrementBAndReturnTwo(){
b++;
return 0;
}
incrementAAndReturnOne() | incrementBAndReturnTwo();
console.log(a); // 1
console.log(b); // I expected 0, but it's 1
Why is that the case?