1

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?

Adelin
  • 7,809
  • 5
  • 37
  • 65
  • 1
    It evaluates each *bit* of the operand against the bit in the same position of the other operand. – deceze May 10 '18 at 10:39
  • Bitwise operator operates on each corresponding bit. So it needs left and right operand. – Zamrony P. Juhara May 10 '18 at 10:43
  • If anything, if *all bits* in the first operand are 1 (e.g. the number `255` as an 8 bit int), then it would never need to evaluate the second operand. But that's not how it's implemented, and bitwise operations don't give any guarantee about short-circuit evaluation (which is an important logical behaviour of boolean operands). – deceze May 10 '18 at 10:50
  • Simply put, the bitwise operants compare the bits of values. So it needs both values. While for some logical operators it's fine to evaluate one at the time. – LukStorms May 10 '18 at 11:01

0 Answers0