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

sadmicrowave picture sadmicrowave · Apr 15, 2010 · Viewed 2.7M times · Source

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.

Answer

Sarfraz picture Sarfraz · Apr 15, 2010

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.