I'm trying to understand the behavior of this code. Can anyone explain it?
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);
}
It seems that without storing a^b
in a variable or wrapping it in parentheses, the code doesn't work as expected.
checkSignsWeird(-50,40);
checkSignsWeird(60,70);
Surprisingly, both calls produce the same result.
Could I be doing something wrong here, or is this possibly a bug? Does bitwise operation behave differently inside an if clause compared to elsewhere in the code? I don't have much experience with bitwise operations, but I thought this approach was elegant based on feedback from another question mentioned here: Check if two integers have the same sign