Is there any differences between
var a;
(a == undefined)
(a === undefined)
((typeof a) == \"undefined\")
((typeof a) === \"undefined\")
Whi
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
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 :)
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
If a is undefined, then
a == undefined
will actually throw an error. Use
(typeof a) === "undefined"
Instead.
I personally like to use
[undefined, null].indexOf(variable) > -1
to check also for null values.
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()
}
}