What is the best way to compare a value against 'undefined'?

前端 未结 6 1867
误落风尘
误落风尘 2020-12-16 21:57

Is there any differences between

var a;
(a == undefined)
(a === undefined)
((typeof a) == \"undefined\")
((typeof a) === \"undefined\")

Whi

相关标签:
6条回答
  • 2020-12-16 22:29

    You should use mentioned above:

    "undefined" === typeof a
    

    But if you have lots of variables to check, your code can get ugly at some point, so you may consider to use Java's approach:

    try { vvv=xxx; zzz=yyyy; mmm=nnn; ooo=ppp; } 
    catch(err){ alert(err.message); }
    

    Obviously alert() shouldn't be used in a production version, but in debugging version it's very useful. It should work even in old browsers like IE 6:

    https://msdn.microsoft.com/library/4yahc5d8%28v=vs.94%29.aspx

    0 讨论(0)
  • 2020-12-16 22:36

    Ironically, undefined can be redefined in JavaScript, not that anyone in their right mind would do that, for example:

    undefined = "LOL!";
    

    at which point all future equality checks against undefined will yeild unexpected results!

    As for the difference between == and === (the equality operators), == will attempt to coerce values from one type to another, in English that means that 0 == "0" will evaluate to true even though the types differ (Number vs String) - developers tend to avoid this type of loose equality as it can lead to difficult to debug errors in your code.

    As a result it's safest to use:

    "undefined" === typeof a
    

    When checking for undefinedness :)

    0 讨论(0)
  • 2020-12-16 22:41
    var a;
    (a == undefined) //true
    (a === undefined) //true
    ((typeof a) == "undefined") //true
    ((typeof a) === "undefined") //true
    

    BUT:

    var a;
    (a == "undefined") //false
    (a === "undefined") //false
    ((typeof a) == undefined) //false
    ((typeof a) === undefined) //false
    
    0 讨论(0)
  • 2020-12-16 22:42

    If a is undefined, then

    a == undefined
    

    will actually throw an error. Use

    (typeof a) === "undefined"
    

    Instead.

    0 讨论(0)
  • 2020-12-16 22:48

    I personally like to use

    [undefined, null].indexOf(variable) > -1
    

    to check also for null values.

    0 讨论(0)
  • 2020-12-16 22:52

    If you declare var a, then it won't be undefined any more - it will be null instead. I usually use typeof a == undefined - and it works fine. This is especially useful in this situation:

    function myfunc(myvar)
    {
        if(typeof myvar == "undefined")
        {
            //the function was called without an argument, simply as myfunc()
        }
    }
    
    0 讨论(0)
提交回复
热议问题