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

前端 未结 30 1483
耶瑟儿~
耶瑟儿~ 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 04:06

    The standard way to catch null and undefined simultaneously is this:

    if (variable == null) {
         // do something 
    }
    

    --which is 100% equivalent to the more explicit but less concise:

    if (variable === undefined || variable === null) {
         // do something 
    }
    

    When writing professional JS, it's taken for granted that type equality and the behavior of == vs === is understood. Therefore we use == and only compare to null.


    Edit again

    The comments suggesting the use of typeof are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try/catch if you are working with input you don't have control over.

    You should not have any references to undeclared variables in your code.

    0 讨论(0)
  • 2020-11-22 04:06
    if (typeof EmpName != 'undefined' && EmpName) {
    

    will evaluate to true if value is not:

    • null

    • undefined

    • NaN

    • empty string ("")

    • 0

    • false

    0 讨论(0)
  • 2020-11-22 04:06

    I run this test in the Chrome console. Using (void 0) you can check undefined:

    var c;
    undefined
    if (c === void 0) alert();
    // output =  undefined
    var c = 1;
    // output =  undefined
    if (c === void 0) alert();
    // output =   undefined
    // check c value  c
    // output =  1
    if (c === void 0) alert();
    // output =  undefined
    c = undefined;
    // output =  undefined
    if (c === void 0) alert();
    // output =   undefined
    
    0 讨论(0)
  • 2020-11-22 04:07

    You can check if the value is undefined or null by simply using typeof:

    if(typeof value == 'undefined'){
    
    0 讨论(0)
  • 2020-11-22 04:10

    You can use the qualities of the abstract equality operator to do this:

    if (variable == null){
        // your code here.
    }
    

    Because null == undefined is true, the above code will catch both null and undefined.

    0 讨论(0)
  • 2020-11-22 04:10

    jQuery attr() function returns either a blank string or the actual value (and never null or undefined). The only time it returns undefined is when your selector didn't return any element.

    So you may want to test against a blank string. Alternatively, since blank strings, null and undefined are false-y, you can just do this:

    if (!EmpName) { //do something }
    
    0 讨论(0)
提交回复
热议问题