Why if([]) is validated while [] == false in javascript?

前端 未结 3 2062
既然无缘
既然无缘 2020-12-01 21:22
if([] == false) alert(\'empty array is false\');
alert(+[]) // alert 0
if([]) alert(\'empty array is true\');

They both will run the alert

3条回答
  •  时光说笑
    2020-12-01 22:01

    It's because of type coercion of the == (equality) operator.

    An empty array is considered truthy (just like an empty object), thus the second alert is called.

    However, if you use ([] == false), your array is coerced to its string representation* which is "" which then is considered as a falsy value, which makes the condition true thus triggering the first alert too.

    If you want to avoid type coercion, you have to use the === (identity) operator which is the preferred and by the famous Douglas Crockford promoted way to compare in javascript.

    You can read more on that matter in this exhaustive answer.

    *(Object.prototype.toString is called on it)

    EDIT: fun with JS-comparison:

    NaN == false // false
    NaN == true  // also false
    NaN == NaN   // false
    
    if(NaN)      // false
    if(!NaN)     // true
    
    0  == '0'     // true
    '' == 0       // true
    '' == '0'     // false !
    

    This shows you the real "power" of Comparison with == due to the strange rules mentioned in bfavarettos answer.

提交回复
热议问题