user1318194
user1318194

Reputation:

JavaScript triple equals and three-variable comparison

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...)

Upvotes: 4

Views: 2217

Answers (2)

Interrobang
Interrobang

Reputation: 17454

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

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173662

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

Upvotes: 7

Related Questions