views:

503

answers:

4

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

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

Use typeof:

if (typeof(EmpName) === 'undefined') {
    // blah blah blah
}
kevingessner
You don’t need to put `EmpName` in parentheses; `typeof` is an operator and not a function.
Gumbo
I know; I just think it reads better this way, and it is valid.
kevingessner
Putting that operand in parentheses is like doing something like this: `(((1)+(1))===(2))`. It’s absolutely valid but also unnecessary.
Gumbo
typeof null = 'object' // true
M28
@Gumbo define unary operator vs unary function.
Evan Carroll
[answer here](http://stackoverflow.com/questions/3786467/why-typeof-is-called-operator-instead-of-function/3786502#3786502)
Evan Carroll
@Evan Carroll: An operator is part of the language syntax; a function part of a language library that is defined using the language syntax.
Gumbo
Is this a general explanation or specific to Javascript? In Haskell (+) is and (-) and part of the standard library. I'm happy with the answer I posted above.. I was just curious I see this point parroted and not explained often.
Evan Carroll
+4  A: 

You can do like this:

 if(typeof variable_here == 'undefined'){
   // your code here.
 };

See more info about typeof operator.

Sarfraz
@ Sarfraz - that works perfectly...but why?...what does typeof do?
sadmicrowave
@sadmicrowave: It checks whether an object is set or not (undefined), see more info about it, i have posted the links for that in my answer. Thanks :)
Sarfraz
@Sarfraz - I dont think that was me....but thanks for answering my question
sadmicrowave
That will only identify the undefined, not the 'null', this is not the correct answer.
M28
A: 

jQuery attr() function returns either a blank string or the actual value (and never null or undefined). The only time it returns undefined is when your selector didn't return any element.

So you may want to test against a blank string. Alternatively, since blank strings, null and undefined are false-y, you can just do this:

if (!EmpName) { //do something }
Chetan Sastry
Care to explain the downvoting?
Chetan Sastry
+2  A: 
if(variable==null){
// Do stuff, will only match null or undefined, this won't match false
}
M28
Just in case anybody thinks this is another half-answer, this actually does work. `undefined` evaluates equal to `null`.
Chuck