how to check falsy with undefined or null?

前端 未结 4 1387
梦谈多话
梦谈多话 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:12

    You can check for falsy values using

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

    Demo: Fiddle


    Or check for truthiness like

    var n = null;
    if (n) { //true if n is truthy
        console.log('has value');
    } else {
        console.log('null');
    }
    

    Demo: Fiddle

提交回复
热议问题