Skip to content Skip to sidebar Skip to footer

How Does Chaining Operators In Javascript Work?

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

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 false

I 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 !== b is evaluated and yields a boolean result, either true if the condition is true or false if it's false. Call that r. In the true, true, true case, true !== true is false so r = false.
  • r !== c is evaluated and yields its boolean result. In the true, true, true case, false !== true is true.

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 !== false

so now the condition is

false !== c  -> thisreturn `true` asfalse !== true

Post a Comment for "How Does Chaining Operators In Javascript Work?"