why checking equality between three strings not works but between three numbers does?

I have checked equality between three numbers in javascript and it works. like:

1 == 1 == 1 //true
2 == 3 == 4 //false
2 == 3 == 3 //false

But when I try this check between three strings, it does not work:

'some string' == 'some string' == 'some string' //false
'a' == 'a' == 'a' //false

Does anyone know why this happens?
Thanks in advance.

2 answers

  • answered 2019-10-22 08:26 CertainPerformance

    Because

    'some string' == 'some string' == 'some string'
    

    evaluates the == operators in left-to-right order. It's equivalent to

    ('some string' == 'some string') == 'some string'
    

    which is

    true == 'some string'
    

    which is false, because when a boolean is compared against something else, according to the spec:

    1. If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.

    When the right-hand side is a string, this resolves to

    1 == 'some string'
    

    which then runs

    1. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).

    but ToNumber('some string') is NaN

    console.log(Number('some string'));

    so the comparison evaluates to false.

    On the other hand, with 1 == 1 == 1, following the same process:

    1 == 1 == 1
    (1 == 1) == 1
    true == 1
    // Rule 8, turn left side into a number:
    1 == 1
    true
    

    Conclusion: Always use ===. If you use ==, you will encounter strange behavior.

  • answered 2019-10-22 08:35 Amit

    1 == 1 == 1 can be interpreted as (1 == 1 (true) == 1) which is true. But 'a' == 'a' == 'a' would be interpreted as ('a' == 'a' (true) == 'a') which would be false. as true is not equal to 'a'.