JavaScript check if value is only undefined, null or false

后端 未结 9 2037
暗喜
暗喜 2021-01-31 08:09

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

相关标签:
9条回答
  • 2021-01-31 08:18

    The best way to do it I think is:

    if(val != true){
    //do something
    } 
    

    This will be true if val is false, NaN, or undefined.

    0 讨论(0)
  • 2021-01-31 08:19

    Boolean(val) === false. This worked for me to check if value was falsely.

    0 讨论(0)
  • 2021-01-31 08:21

    Using ? is much cleaner.

    var ? function_if_exists() : function_if_doesnt_exist();
    
    0 讨论(0)
  • 2021-01-31 08:22

    I think what you're looking for is !!val==false which can be turned to !val (even shorter):

    You see:

    function checkValue(value) {
        console.log(!!value);
    }
    
    checkValue(); // false
    checkValue(null); // false
    checkValue(undefined); // false
    checkValue(false); // false
    checkValue(""); // false
    
    checkValue(true); // true
    checkValue({}); // true
    checkValue("any string"); // true
    

    That works by flipping the value by using the ! operator.

    If you flip null once for example like so :

    console.log(!null) // that would output --> true
    

    If you flip it twice like so :

    console.log(!!null) // that would output --> false
    

    Same with undefined or false.

    Your code:

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

    would then become:

    if(!val) {
      ;
    }
    

    That would work for all cases even when there's a string but it's length is zero. Now if you want it to also work for the number 0 (which would become false if it was double flipped) then your if would become:

    if(!val && val !== 0) {
      // code runs only when val == null, undefined, false, or empty string ""
    }
    
    0 讨论(0)
  • 2021-01-31 08:24

    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.

    0 讨论(0)
  • 2021-01-31 08:26

    Another solution:

    Based on the document, Boolean object will return true if the value is not 0, undefined, null, etc. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

    If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

    So

    if(Boolean(val))
    {
    //executable...
    }
    0 讨论(0)
提交回复
热议问题