how to check falsy with undefined or null?

前端 未结 4 1377
梦谈多话
梦谈多话 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条回答
  •  梦毁少年i
    2021-01-19 04:05

    To solve your problem:

    You can use not operator(!):

    var n = null;
    if(!n){ //if n is undefined, null or false
    console.log('null');
    } else{
    console.log('has value');
    }
    // logs null
    

    To answer your question:

    It is considered falsy or truthy for Boolean. So if you use like this:

    var n = Boolean(null);
    if(n===false){
    console.log('null');
    } else{
    console.log('has value');
    }
    //you'll be logged null
    

提交回复
热议问题