Search code examples
programming-languagesscripting-language

Why in JavaScript and so in other programming languages is not possible to do if (a==b==c) to compare 3 variable at once?


Why, objectively, in programming languages in general, as far as I know, isn't possibile to compare 3 variable at once doing something like this:

if(a == b == c)
{
   do something;
}

but it is necessary to do something like:

if(a == b && b == c)
{
   do something;
}

why it is necessary to repeat twice the b variable?

Why the simplified way isn't implemented as well to compare multiple variables but is is necessary to use logic operators to make the comparison work?

The same question can be raised inequalities as a > b > c etc...


Solution

  • It has to do with the way the language evaluates boolean values. There are two different ways it could evaluate a == b == c: (a == b) == c, or a == (b == c).

    In the first case, (a == b) == c, we start by evaluating a == b, which will return either true or false. The problem comes in when we try to do the next step. After evaluating what was in the parentheses, we could have either true == c or false == c, and unless c was equal to either true or false, the result of that (and the entire expression) would be false.

    Hopefully you can see how this also applies to both ways of evaluating the expression, as well as with any other comparison operators you may use. Comparison operators simply return true or false based on the values directly to either side of them, and scripting languages run expressions in order, not all at once.

    Another way to see it is if you rewrote the == operator as a function:

    function isEqual(a, b):
      if a == b:
        return true
      else:
        return false
    

    That is pretty much exactly what the == operator does. It simply returns true or false based on the values of its two arguments. Writing a == b == c would be the same as writing either isEqual(isEqual(a, b), c) or isEqual(a, isEqual(b, c)). Either way, you would be comparing a boolean to a potentially other type of value.