views:

25454

answers:

12

What's the best way of checking if an object property in JavaScript is undefined?

Sorry, I initially said variable rather than object property. I believe the same == undefined approach doesn't work there.

A: 
if (somevariable == undefined) {
  alert('the variable is not defined!');
}

You can also make it into a function, as shown here:

function isset(varname){
  return(typeof(window[varname]) != 'undefined');
}
tj9991
First, when somevariable equals undefined, it doesn't mean the variable is undefined - it's just the value that is undefined. When the variable is undefined, then this code will throw an error. Second, this isset function will only work for global variables.
Rene Saarsoo
Use `===` over `==`
trinithis
+13  A: 

In JavaScript there is null and there is undefined. They have different meanings.

  • undefined means that the variable value has not been defined; it is not known what the value is.
  • null means that the variable value is defined and set to null (has no value).

Marijn Haverbeke states, in his free, online book "Eloquent JavaScript" (emphasis mine):

There is also a similar value, null, whose meaning is 'this value is defined, but it does not have a value'. The difference in meaning between undefined and null is mostly academic, and usually not very interesting. In practical programs, it is often necessary to check whether something 'has a value'. In these cases, the expression something == undefined may be used, because, even though they are not exactly the same value, null == undefined will produce true.

So, I guess the best way to check if something was undefined would be:

if (something == undefined)

Hope this helps!

Edit: In response to your edit, object properties should work the same way.

var person = {
    name: "John",
    age: 28,
    sex: "male"
};

alert(person.name); // "John"
alert(person.fakeVariable); // undefined
Pandincus
if (something == undefined)is better written as if (something === undefined)
Sebastian Rittau
Saying "undefined means that the variable has not been defined; it does not exist" (2nd line) is plain wrong. When a variable is not defined and you try to know its value, javascript throws a "is not defined" exception. **undefined** means that the variable _value_ has not been defined. So the variable value is unknown ; it is not known if the variable has a value and what it is. And **null** means that the variable _value_, which is defined, is null. So the variable has no value ; it is known that the variable doesn't have a value.
Alsciende
@Alsciende good points, I changed the wording slightly.
Pandincus
It should be pointed out that this is not entirely safe. `undefined` is just a variable that can be re-assigned by the user: writing `undefined = 'a';` will cause your code to no longer do what you think it does. Using `typeof` is better and also works for variables (not just properties) that haven't been declared.
Gabe Moothart
if something is an undefined global variable, (something == undefined) brings up javascript error.
Morgan Cheng
+11  A: 

It's better to use the strict equality operator:

if (variable === undefined) {
   alert('not defined');
}

x == undefined also checks whether x is null, while strict equality does not (if that matters).(source)

Or you can simply do this:

if (!variable) {
   alert('not defined');
}

Here you check if there's any value that can make the variable look false (undefined, null, 0, false, ...). Not a good method for integers ('0' is not false), but might do well for object properties.

Berzemus
shouldn't it be if (!variable) {alert ('not defined');} ?
Nathan Feger
Checking for a truly undefined variable this way *will* cause an error to be thrown. It will work if the variable was set explicitly to undefined, but if the variable was never set, it's necessary to use typeof as @Erwin pointed out.
Ben
@Ben is right. I don't know how this got voted up so much. This is really bad code.
Wahnfrieden
+5  A: 

The solution is incorrect. In javascript,

null == undefined

will return true because they both are "casted" to a boolean and are false. The correct way would be to check

if (something === undefined)

which is the identity operator...

Ricky
To be clear, `===` is type equality + (primitive equality | object identity), where primitives include strings. I think most people consider `'abab'.slice(0,2) === 'abab'.slice(2)` unintuitive if one considers `===` as the identity operator.
clacke
+35  A: 

Use:

if (typeof something  == "undefined") 
   alert("something is undefined");
`typeof` is an operator not a function, so braces are not needed.
Rene Saarsoo
Poor Erwin, missing out an all this rep!
Daniel Schaffer
You should use `===` not `==`.
The Doctor What
@The Doctor What: it's not necessary here... typeof always gives a string, and a string literal always gives a string, so == and === work identically in situations like this.
no
A: 

I've tested with undefined but is not recognized on object as standard command (i probably wrong same case sensitive), as said Ricky undefined = null. I've tested with null and finally work:

document.getElementById("objectname") === null

I've used it to check(uncheck) unknown number of checkboxes without test all objects in the page.

Am4dEuZ
A: 
function isUnset(inp) {
  return !!(typeof inp === 'undefined')
}

return false if variable is set, and true if is undefined.

use::

if (isUnset(var)){
  //Handle initialization
}
Rixius
The `!!` is not necessary. `===` returns a boolean value.
clacke
You're absolutely correct. >.>
Rixius
+2  A: 
if ( typeof( something ) == "undefined") 

This worked for me while the others didn't.

Kevin
parens are unnecessary since typeof is an operator
Wahnfrieden
+1  A: 

I believe there are a number of incorrect answers to this topic. Contrary to common belief "undefined" is NOT a keyword in javascript, and can in fact have a value assigned to it.

var undefined = false;
if(myVar === undefined) { // <-- undefined should not be blue text
 alert("it was undefined");
}

Additionally, "myVar === undefined" will raise an error in the situation where myVar is undeclared.

The most robust way to perform this test is:

if(typeof myVar === "undefined")

This will always return the correct result, and even handles the situation where myVar is not declared.

Mark
A: 

Please try the following example it works for me and it is as per w3schools standard

var t1;
if (t1 == undefined) {
   alert('not defined');
}
Mahnedra
A: 

I'm not sure where the origin of using === with typeof came from, and as a convention I see it used in many libraries, but the typeof operator returns a string literal, and we know that up front, so why would you also want to type check it too?

typeof x; // some string literal "string", "object", "undefined" if (typeof x === "string") { // === is redundant because we already know typeof returns a string literal if (typeof x == "string") { // sufficient

Eric
A: 

I concur with @Mark

Sid