Is NaN falsy? Why NaN === false returns false

前端 未结 7 842
走了就别回头了
走了就别回头了 2020-12-13 18:43
  1. Why NaN === false => false, isn\'t NaN falsy?
  2. Why NaN === NaN => false, but !!NaN === !!NaN => true

I\'v

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 19:26

    1.Why NaN === false => false, isn't NaN falsy?

    The term "falsy" isn't defined in ECMA-262, it's jargon for where type conversion coerces a value to false. e.g.

    var x = NaN;
    
    if (!x) {
      console.log('x is "falsy"');
    }
    

    The strict equality operator uses the Strict Equality Comparison Algorithm which checks that the arguments are of the same Type, and NaN is Type number, while false is Type boolean, so they evaluated as not equal based on Type, there is no comparison of value.

    2.Why NaN === NaN => false, but !!NaN === !!NaN => true

    Because the strict equality comparison algorithm states that NaN !== NaN, hence the isNaN method.

    Using ! coerces the argument to boolean using the abstract ToBoolean method, where !NaN converts to true and !!NaN converts to false, so:

    !!NaN === !!NaN  -->  false === false  -->  true
    

    Note that the abstract equality operator == will coerce the arguments to be of the same Type according to the rules for the Abstract Equality Comparison Algorithm. In this case, NaN is Type number, so false is converted to a number using toNumber which returns 0. And 0 is not equal to NaN so:

    NaN == false  -->  NaN == 0  -->  false
    

提交回复
热议问题