1

I am using JavaScript and I want to check equality of the variable values within if condition. It can check equality of two variables but I don't know how to do it with multiple variables. I like to express it as follows but it wrong. Is there a way to check this?

var a = 2, b = 2, c = 2, d = 2, e = 2, f = 1; if(a == b == c == d == e == f){ console.log("All values are equel"); }else{ console.log("Values are not equel"); } 
2
  • You are looking for a logical AND: if (a === b && a === c && ...) Commented Jan 19, 2017 at 8:56
  • 2
    in case you could collect these variables inside an array, you could go for something like this: if (yourArray.every(function(v) { return v === yourArray[0]; })) Commented Jan 19, 2017 at 8:59

5 Answers 5

4

Since equality is a transitive relation, you can:

if(a == b && b == c && c == d && d == e && e == f ){ console.log("All values are equal"); } else { console.log("Not all values are equal"); } 
Sign up to request clarification or add additional context in comments.

Comments

3

You should use if(a == b && a == c && ...)

Comments

2

You could use Array#every and check the values in an array.

var a = 2, b = 2, c = 2, d = 2, e = 2, f = 1; if ([a, b, c, d, e, f].every(function (a, i, aa) { return aa[0] === a; })) { console.log("All values are equal"); } else { console.log("Values are not equal"); }

1 Comment

Yes this is the optimal solution for my case.
2
var a = 2, b = 2, c = 2, d = 2, e = 2, f = 1; if((a == b) && (a ==c) && (a==d) && (a == e) && (a==f) && (b==c) &&(b==d)&&(b==e)&&(b==f)&&(c==d)&&(c==e)&&(c==f)&&(d==f)&&(d==e)&&(d==f)&&(e==f)){ console.log("All values are equel"); }else(){ console.log("Values are not equel"); } 

Comments

1

You need to compare the variables 2 by 2. So it should be something like

if(a == b && b == c && c == d && d == e && e == f){ your code } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.