Search code examples
javascripttriple-equals

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


Solution

  • 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