how to check falsy with undefined or null?

前端 未结 4 1482
梦谈多话
梦谈多话 2021-01-19 03:32

undefined and null are falsy in javascript but,

var n = null;
if(n===false){
console.log(\'null\');
} else{
console.log(\'has value\');
}

b

4条回答
  •  没有蜡笔的小新
    2021-01-19 04:15

    A value being "falsy" means that the result of converting it to a Boolean is false:

    Boolean(null) // false
    Boolean(undefined) // false
    // but
    Boolean("0") // true
    

    This is very different from comparing it against a Boolean:

    null == false // not equal, null == true is not equal either
    undefined == false // not equal, undefined == true is not equal either
    // but
    "0" == true // not equal, however, `"0" == false` is equal
    

    Since you are using strict comparison, the case is even simpler: the strict equality comparison operator returns false if operands are not of the same data type. null is of type Null and false is of type Boolean.

    But even if you used loose comparison, the abstract equality algorithm defines that only null and undefined are equal to each other.


    Depending on what exactly you want to test for, you have a couple of options:

    if (!value)         // true for all falsy values
    
    if (value == null)  // true for null and undefined
    
    if (value === null) // true for null
    

    In general you should always prefer strict comparison because JS' type conversion rules can be surprising. One of the exceptions is comparing a value against null, since loose comparison also catches undefined.

提交回复
热议问题