-1

Is there an easy way to compare three values in an if statement something like

if(value1==value2==value3) {}

Or in my case

if(var1==var2=="0") {}
CoolAsFinnBro
  • 11
  • 1
  • 2

4 Answers4

2

It can't be done in the manner you are describing ( val1 == val2 == val3 ) since javascript evaluates left to right in a greedy fashion. This means that your "if" statement is actauly checking whether the outcome of "val1 == val2" evaluates to "val3" (so if val1 equals val2, it would check if "val3" evaluates to "true", otherwise it would check if "val3" evaluates to "false").

To compare 3 variables in an "if" statement, you would need to use a combined logical "AND" ("&&") check. if(value1==value2 && value2==value3) {}

Eyal
  • 532
  • 2
  • 12
0

You can simply extend your if with two conditions:

if (var1 === '0' && var2 === '0') {
    // code
}

If you have to much variables:

var isZeroes = true;

[var1, var2, /* ... */].map(function(item)  {
    if (item !== '0') isZeroes = false;
});

if (isZeroes) {
    // ..code
}
Boris Zagoruiko
  • 12,705
  • 15
  • 47
  • 79
0

To compare multiple number of variables, you can use custom "isEqual" function.

function isEqual() {
   var len = arguments.length;
   for (var i = 1; i < len; i++) {
      if (arguments[i] == null || arguments[i] != arguments[i-1])
         return false;
   }
   return true;
}

...
if (isEqual(a, b, c, d)) {
  ...
}

In order to compare just 3 values, just use: if (a == b && b == c)

Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64
0

you can do it this way:

if (var1==var2)
{
 if (var1=='0')
   {
      // var1 and var2 equal to 0
   }
}