0

Could somebody explain this behavior?

https://jsfiddle.net/td1qtyxL/9/

function checkSignsWeird(a,b){
    var output = "";
    if(a^b < 0){
        output = "The "+a+" and "+b+" have DIFFERENT signs.";
    }else{
        output = "The "+a+" and "+b+" have the SAME sign.";
    }
    console.log(output);
}

Basically unless a^b is stored in a variable (or wrapped in parentheses), it doesn't work.

checkSignsWeird(-50,40);
checkSignsWeird(60,70);

Both produce the same result.

Amy I doing something wrong or is this a bug? Does bitwise work differently when it's in an if clause or when it's elsewhere? I don't often work with bitwise, just thought this was elegant, following up on an answer from here: Check if two integers have the same sign

Community
  • 1
  • 1

2 Answers2

2

The "Less Than" (<) has a higher precedence than the bitwise XOR (^): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table

You need to group the operation with parentheses.

stesch
  • 7,202
  • 6
  • 47
  • 62
  • 1
    So what is does without parentheses is that it first checks if `b < 0` (b is 40 or 70), evaluates it to `false` then continues by doing `-50^false` which is `-50` that counts as true... Just to test if I understood correctly I ran `checkSignsWeird(0,1);` and it finally shown the result from the else branch. `1 < 0` means false then it does `0^false` which evaluates to `0` which is in turn false. Nice. – Firsh - justifiedgrid.com Apr 26 '17 at 14:42
2

Bitwise operators have a lower precedence than comparison operators. See Operator precedence.

That being said, don't write clever code.

function haveSameSign(a, b) {
    return (a >= 0 && b >= 0) || (a < 0 && b < 0);
}
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Why not? Isn't this how we learn? Is there a scenario where clever is preferred over the trivial solution? – Firsh - justifiedgrid.com Apr 26 '17 at 14:34
  • "Clever" code is non-obvious, hard to maintain, error-prone and usually serves no purpose other than stroking the ego of the one who wrote it. Avoid. Write dead-obvious code that does not need comments to be understood. – Tomalak Apr 26 '17 at 14:41