HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howdetermineundefinedvariablecannull

Problem

How do I determine if a variable is undefined or null?

My code is as follows:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};






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

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#2647867, score: 3581

Revisions (0)

No revisions yet.