JavaScript check if value is only undefined, null

2019-03-08 18:16发布

Other than creating a function, is there a shorter way to check if a value is undefined,null or false only in JavaScript?

The below if statement is equivalent to if(val===null && val===undefined val===false) The code works fine, I'm looking for a shorter equivalent.

if(val==null || val===false){
  ;
}

Above val==null evaluates to true both when val=undefined or val=null.

I was thinking maybe using bitwise operators, or some other trickery.

9条回答
做自己的国王
2楼-- · 2019-03-08 18:55

Using ? is much cleaner.

var ? function_if_exists() : function_if_doesnt_exist();
查看更多
Emotional °昔
3楼-- · 2019-03-08 19:02

One way to do it is like that:

var acceptable = {"undefined": 1, "boolean": 1, "object": 1};

if(!val && acceptable[typeof val]){
  // ...
}

I think it minimizes the number of operations given your restrictions making the check fast.

查看更多
Bombasti
4楼-- · 2019-03-08 19:04

Well, you can always "give up" :)

function b(val){
    return (val==null || val===false);
}
查看更多
登录 后发表回答