4

Can somebody explain this?

1 == 1        //true, as expected
1 === 1       //true, as expected
1 == 1 == 1   //true, as expected
1 == 1 == 2   //false, as expected
1 === 1 === 2 //false, as expected
1 === 1 === 1 //false? <--

Also is there a name for boolean logic that compares more than two numbers in this way (I called it "three-variable comparison" but I think that'd be wrong...)

2 Answers2

7

This expression:

1 === 1 === 1

Is evaluated as:

(1 === 1) === 1

After evaluating the expression inside parentheses:

true === 1

And that expression is logically false. The below expression returns true as expected though:

1 === 1 === true
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 2
    Haha, should have tested more: `5 == 5 == 5` is also false, but because `1 == true` I was getting tripped up using my example of `1 == 1 == 1`. +1 thanks! –  Mar 11 '13 at 05:52
  • One more question: can I do what I want to do without a tedious expression (such as `x === y && y === z && x === z`)? –  Mar 11 '13 at 05:57
  • @DuncanNZ Are there always three variables involved? – Ja͢ck Mar 11 '13 at 05:59
  • yes - basically I need to check that 3 strings are all equal to eachother –  Mar 11 '13 at 06:01
  • @DuncanNZ You can work with the fact that `===` is transitive, so `x === y && x === z` would be enough. – Ja͢ck Mar 11 '13 at 06:02
  • so what is the shortest way to compare 3 variables? – vsync May 09 '13 at 09:59
  • 1
    @vsync Generally, to compare N distinct variables for equality (N > 1) you need N - 1 comparisons. – Ja͢ck May 09 '13 at 12:52
1

Equality is a left-to-right precedence operation.

So:

1 == 1 == 1
true == 1
true

And:

1 === 1 === 1
true === 1
false // because triple-equals checks type as well
Interrobang
  • 16,984
  • 3
  • 55
  • 63