How can I determine if a variable is 'undefined' or 'null'?

前端 未结 30 1474
耶瑟儿~
耶瑟儿~ 2020-11-22 03:30

How do I determine if variable is undefined or null?

My code is as follows:

var EmpN         


        
相关标签:
30条回答
  • 2020-11-22 03:52

    jQuery check element not null:

    var dvElement = $('#dvElement');
    
    if (dvElement.length  > 0) {
        // Do something
    }
    else{
        // Else do something else
    }
    
    0 讨论(0)
  • 2020-11-22 03:52

    To test if a variable is null or undefined I use the below code.

        if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
          console.log('variable is undefined or null');
        }
    
    0 讨论(0)
  • 2020-11-22 03:52
    var x;
    if (x === undefined) {
        alert ("only declared, but not defined.")
    };
    if (typeof y === "undefined") {
        alert ("not even declared.")
    };
    

    You can only use second one: as it will check for both definition and declaration

    0 讨论(0)
  • 2020-11-22 03:53

    You can simply use the following (I know there are shorter ways to do this, but this may make it easier to visually observe, at least for others looking at the code).

    if (x === null || x === undefined) {
     // Add your response code here, etc.
    }
    
    0 讨论(0)
  • 2020-11-22 03:54

    The foo == null check should do the trick and resolve the "undefined OR null" case in the shortest manner. (Not considering "foo is not declared" case.) But people who are used to have 3 equals (as the best practice) might not accept it. Just look at eqeqeq or triple-equals rules in eslint and tslint...

    The explicit approach, when we are checking if a variable is undefined or null separately, should be applied in this case, and my contribution to the topic (27 non-negative answers for now!) is to use void 0 as both short and safe way to perform check for undefined.

    Using foo === undefined is not safe because undefined is not a reserved word and can be shadowed (MDN). Using typeof === 'undefined' check is safe, but if we are not going to care about foo-is-undeclared case the following approach can be used:

    if (foo === void 0 || foo === null) { ... }
    
    0 讨论(0)
  • 2020-11-22 03:55

    In JavaScript, as per my knowledge, we can check an undefined, null or empty variable like below.

    if (variable === undefined){
    }
    
    if (variable === null){
    }
    
    if (variable === ''){
    }
    

    Check all conditions:

    if(variable === undefined || variable === null || variable === ''){
    }
    
    0 讨论(0)
提交回复
热议问题