JavaScript equality transitivity is weird

后端 未结 3 699
长情又很酷
长情又很酷 2020-12-01 04:08

I\'ve been reading Douglas Crockford\'s JavaScript: The Good Parts, and I came across this weird example that doesn\'t make sense to me:

\'\' == \'0\'                


        
3条回答
  •  我在风中等你
    2020-12-01 04:48

    '' == '0' // false
    

    The left hand side is an empty string, and the right hand side is a string with one character. They are false because it is making a comparison between two un identical strings (thanks Niall).

    0 == '' // true
    

    Hence, why this one is true, because 0 is falsy and the empty string is falsy.

    0 == '0' // true
    

    This one is a bit trickier. The spec states that if the operands are a string and a number, then coerce the string to number. '0' becomes 0. Thanks smfoote.

    false == undefined // false
    

    The value undefined is special in JavaScript and is not equal to anything else except null. However, it is falsy.

    false == null // false
    

    Again, null is special. It is only equal to undefined. It is also falsy.

    null == undefined // true
    

    null and undefined are similar, but not the same. null means nothing, whilst undefined is the value for a variable not set or not existing. It would kind of make sense that their values would be considered equal.

    If you want to be really confused, check this...

    '\n\r\t' == 0
    

    A string consisting only of whitespace is considered equal to 0.

    Douglas Crockford makes a lot of recommendations, but you don't have to take them as gospel. :)

    T.J. Crowder makes an excellent suggestion of studying the ECMAScript Language Specification to know the whole story behind these equality tests.

    Further Reading?

    The spec.

    yolpo (on falsy values)

提交回复
热议问题