How Does Chaining Operators In Javascript Work?
Solution 1:
This solution seems to work, but my question is... why?
It doesn't work for what you described (only one can be true, and one must be true); it fails in the true, true, true case:
functionisValid(a, b, c) { return a !== b !== c; }
console.log(isValid(true, true, true)); // true, should be falseI should note that I don't think your rule is quite the same as XOR, since true XOR true XOR true is true (because true XOR true is false, and false XOR true is true).
a !== b !== c is evaluated like this:
a !== bis evaluated and yields abooleanresult, eithertrueif the condition is true orfalseif it's false. Call thatr. In thetrue, true, truecase,true !== trueisfalsesor = false.r !== cis evaluated and yields itsbooleanresult. In thetrue, true, truecase,false !== trueistrue.
As you can see from the above, it works in almost all XOR cases, but not when all the inputs are true. It also doesn't work for other examples. Probably the most common error people make is trying to see if a, b, and c all have the same value:
if (a === b === c) // WRONG (almost always)Since that's ((a === b) === c) which is (some_boolean === c), it's almost always wrong (for instance, if a, b, and c contain anything but boolean values).
Solution 2:
Since the operator are of same precedence so the Associativity decides how this is going to be evaluate Operator precedence
functionisValid(a, b, c) { return a !== b !== c; }
var one = false;
var two = false;
var three = true;
You can understand it step by step
a !== b -> thisreturn `false` asfalse !== falseso now the condition is
false !== c -> thisreturn `true` asfalse !== true
Post a Comment for "How Does Chaining Operators In Javascript Work?"