How to determine if variable is 'undefined' or 'null'?

How do I determine if variable is undefined or null ? My code is as follows:

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  //DO SOMETHING
};
<div id="esd-names">
  <div id="name"></div>
</div>

But if I do this, the JavaScript interpreter halts execution.


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 .


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 === ][1] 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.

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


if (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}
链接地址: http://www.djcxy.com/p/2138.html

上一篇: 在调用instanceof之前是否需要空值检查?

下一篇: 如何确定变量是'undefined'还是'null'?