I was looking to XOR three boolean variables. Only one can be true, and one must be true:
function isValid(a, b, c) { return a !== b !== c; }
var one = false;
var two = false;
var three = true;
console.log(isValid(one, two, three)); // should be true
one = true;
console.log(isValid(one, two, three)); // should be false
This solution seems to work, but my question is... why? Shouldn't it fail if all values are false?
var one = false;
var two = false;
var three = false;
console.log(isValid(one, two, three)); // should be true, but it is false
Additionally, all variables being true, returns true when it should return false.
var one = true;
var two = true;
var three = true;
console.log(isValid(one, two, three)); // should be false, but it's true
My thought is that it executes thusly:
a !== b? TRUE
TRUE !== c? TRUE
Clearly that isn't how it works, so how does it work?
a !== b !== cmeans(a !== b) !== c, and(a !== b)yields a boolean value, and that value is what's compared toc.a !== bthis isfalse, since both elements have the valuefalse. Then you getfalse !== c, which is alsofalse, sincechas the valuefalse. So your solution does not do what you think it does.true, you get( true !== true ), which is false. And thenfalse !== true, which is true.a !== b && a !== c && b !== c