How does JS type coercion work?

后端 未结 2 1230
轮回少年
轮回少年 2020-11-28 16:19

I\'m learning about == vs. === and came across this answer which was very helpful in understanding the concept. However I wondered about one of the

相关标签:
2条回答
  • 2020-11-28 16:31

    To make things more confusing for totally new in programming world:

    Boolean('false')
    true
    
    Boolean('true')
    true
    

    I think it is easier and more intuitive to use !! operator for some reason. I dont know if i make sense, but i never used Boolean()

    Answering the question, i found that thread useful: Difference between == and === in JavaScript

    0 讨论(0)
  • 2020-11-28 16:46

    "0" is a string containing the character 0, it is not the numeric value 0. The only string-type value which evaluates to false is "".

    "0" is truthy.

    Section 9.2 of the ECMAScript 262 specification defines how different types are converted to Boolean:

    Argument Type   Result
    Undefined       false
    Null            false
    Boolean         The result equals the input argument (no conversion).
    Number          The result is false if the argument is +0, −0, or NaN; otherwise the
                    result is true.
    String          The result is false if the argument is the empty String (its length is
                    zero); otherwise the result is true.
    Object          true
    

    This, however, is only strictly followed when comparing using ===.

    When using Boolean('0') you're converting the value '0' to Boolean (which is the same as using !!'0'). When loosely comparing '0' with false, the Boolean value is converted to a number (as defined here). false, when converted to a number, becomes 0. This means the final calculation is '0' == 0 which equates to true.

    To summarise the relevant part of the linked section of the ECMAScript specification above:

    1. Let x = '0' and y = false.
    2. Check if the type of y is Boolean.
    3. If true, convert y to a number.
    4. Compare x to the numeric equivalent of y.

    In our case, a JavaScript implementation of this would be:

    var x = '0',                      // x = "0"
        y = false;                    // y = false
    
    if (typeof y === "boolean") {
        y = +y;                       // y = 0
    }
    
    console.log( x == y );            // "0" == 0
    
    -> true
    
    0 讨论(0)
提交回复
热议问题