Why does “undefined equals false” return false?

后端 未结 7 1067
借酒劲吻你
借酒劲吻你 2020-11-30 06:28

When I compare undefined and null against Boolean false, the statement returns false:

undefined == false;
null == false;

It return false. W

相关标签:
7条回答
  • 2020-11-30 07:08

    With the original answer pointing to the spec being deleted, I'd like to provide a link and short excerpt from the spec here.

    http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

    The ECMA spec doc lists the reason that undefined == false returns false. Although it does not directly say why this is so, the most important part in answering this question lies in this sentence:

    The comparison x == y, where x and y are values, produces true or false.
    

    If we look up the definition for null, we find something like this:

    NULL or nil means "no value" or "not applicable".
    

    In Javascript, undefined is treated the same way. It is without any value. However, false does have a value. It is telling us that something is not so. Whereas undefined and null are not supposed to be giving any value to us. Likewise, there is nothing it can convert to for its abstract equality comparison therefore the result would always be false. It is also why null == undefined returns true (They are both without any value). It should be noted though that null === undefined returns false because of their different types. (Use typeof(null) and typeof(undefined) in a console to check it out)

    What I'm curious of though, is that comparing NaN with anything at all will always return false. Even when comparing it to itself. [NaN == NaN returns false]

    Also, another odd piece of information: [typeof NaN returns "number"]


    Strict Equality

    If possible, you should avoid using the == operator to compare two values. Instead use === to truly see if two values are equal to each other. == gives the illusion that two values really are exactly equal when they may not be by using coercion. Examples:

    5 == "5" is true

    5 === "5" is false

    "" == false is true

    "" === false is false

    0 == false is true

    0 === false is false

    0 讨论(0)
提交回复
热议问题