Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
45  
o.prop === undefined is the way to go, or typeof(o.prop) == 'undefined' if there is a risk somebody might define a variable by the name undefined. There is a lot of confusion in the answers. Note that o.prop == undefined will give true if o.prop is defined with the value null. – clacke Jul 30 '10 at 8:58
1  
This question is a candidate for merging a duplicate question. Would it be possible to mark as the accepted answer the one that is actually correct? – Robert Harvey Aug 2 '10 at 18:15
2  
A more complete answer is here: stackoverflow.com/questions/3390396/… – makerofthings7 Nov 2 '10 at 22:11
3  
Note that if the property is not set at all on the object, then typeof(o.prop) == 'undefined' is still true. To distinguish this case, you need to check 'prop' in o. – Dave Feb 19 '12 at 9:34
Best answer ever - stackoverflow.com/questions/2631001/… – Rodrigo Dias Nov 9 '12 at 18:08
show 1 more comment

15 Answers

up vote 849 down vote accepted

Use:

if (typeof something === "undefined") 
   alert("something is undefined");
share|improve this answer
6  
What happens if something is null? Usually you want to check if something if either null or undefined. – Cristian Vrabie May 16 '12 at 14:19
4  
if something is null the it is defined (as null), but you can conjugate the too checks. The annoying detail of the above code is that you can't define a function to check it, well you can define the function... but try to use it. – neu-rah Jun 25 '12 at 19:20
2  
Why not, ravz? Could you please elaborate? – Thiago Ganzarolli Aug 26 '12 at 2:31
3  
@neu-rah why can't you write a function? why wouldn't something like this work? It seems to work for me. Is there a case I'm not considering? jsfiddle.net/djH9N/6 – Zack Sep 24 '12 at 19:01
6  
stackoverflow.com/a/3550319/122718 is a much better answer to this question because it provides the rationale. – usr Oct 2 '12 at 12:16
show 6 more comments
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');
}
share|improve this answer
7  
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 Jan 26 '10 at 23:09
2  
Use === over == – Thomas Eding Aug 2 '10 at 18:40

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
share|improve this answer
17  
if (something == undefined) is better written as if (something === undefined) – Sebastian Rittau Nov 30 '09 at 9:47
8  
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 Apr 1 '10 at 10:18
29  
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 Apr 14 '10 at 15:18
2  
if something is an undefined global variable, (something == undefined) brings up javascript error. – Morgan Cheng Apr 21 '10 at 3:04
2  
The problem with this is that if var a = null then a == undefined evaluates to true, even though a is most certainly defined. – Andrew May 19 '11 at 18:50
show 3 more comments

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.

share|improve this answer
7  
shouldn't it be if (!variable) {alert ('not defined');} ? – Nathan Feger Oct 26 '09 at 21:30
10  
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 Apr 6 '10 at 16:52
6  
@Ben is right. I don't know how this got voted up so much. This is really bad code. – aehlke Aug 10 '10 at 11:20

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...

share|improve this answer
1  
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 Jul 30 '10 at 8:49
Wrong. This throws an error if the variable has not been created. Should not be voted up. Use typeof instead. – Simon Jun 15 '11 at 0:22
function isUnset(inp) {
  return (typeof inp === 'undefined')
}

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

Then use:

if (isUnset(var)) {
  // initialize variable here
}
share|improve this answer
3  
The !! is not necessary. === returns a boolean value. – clacke Jul 30 '10 at 8:27
You're absolutely correct. >.> – Rixius Jul 30 '10 at 8:35
Submitted corrections to code, based on comments above. Thanks clacke. – Simon Jun 15 '11 at 0:36
if ( typeof( something ) == "undefined") 

This worked for me while the others didn't.

share|improve this answer
21  
parens are unnecessary since typeof is an operator – aehlke Aug 10 '10 at 11:22
6  
But they make it clearer what is being checked. Otherwise it might be read as typeof (something == "undefined"). – Abhi Beckert Sep 6 '12 at 0:28
i like the parens because im a "c#-er" coder – Valamas - AUS Jan 30 at 23:16

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.

// Degenerate code. DO NOT USE.
var undefined = false;  // Shockingly, this is completely legal!
if(myVar === undefined) {
 alert("You have been mislead. Run away!");
}

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.

share|improve this answer
22  
+1 for noting that myVar === undefined will raise an error if myVar was not declared – Enrique Dec 19 '11 at 18:27
3  
yes - the QUOTES are apparently vital. my guess is that the typeof function returns a string (of expected format) – jsh Mar 22 '12 at 19:02
I agree that undefined is not a keyword, undefined is a predefined variable with an undefined value. Something like alert, this is a function that you can override with something else. Alert is also not a keyword but a part of the standard function set, ap part of the window object that has a global scope. Like undefined you can also override the alert function by re-assigning it. For example: window.alert = function(s) { console.log(s); } is also a legal construction. – Erwinus Nov 8 '12 at 6:49
3  
I find the first justification given here for not using === undefined bewildering. Yes, you can assign to undefined, but there is no legitimate reason to do so, and it's predictable that doing so may break your code. In C you can #define true false, and in Python you can assign to True and False, but people don't feel the need to design their code in those languages in such a way as to protect against the possibility of themselves deliberately sabotaging their own environment elsewhere in the code. Why is the possibility of assigning to undefined even worth considering here? – Mark Amery Jan 13 at 19:05
@Mark Amery: Ask the JQuery guys. They make effort to ensure that they get a clean variable that is undefined rather than depend on the "global" undefined variable. I assume their reasoning is that they are developing a library that may be consumed by developers with a varied levels of experience, some of whom may not realize what 'undefined' even means. It would be most unfortunate if JQuery exhibited a bug because of their external code. Look at the first and last lines of unminified JQuery to see what I mean. – Mark Jan 14 at 17:10
show 1 more comment

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
share|improve this answer
Great point Eric. Is there a performance hit from checking type also? – Simon Jun 29 '11 at 7:16
   
@Simon: quite the contrary - one could expect slight performance hit from avoiding coercion in '===' case. Quick and dirty test has shown '===' is 5% faster than '==' under FF5.0.1 – Antony Hatchkins Dec 18 '11 at 8:24
2  
More thorough test has shown that under FF,IE and Chrome '==' is more or less faster than '===' (5-10%) and Opera doesn't make any difference at all: jsperf.com/triple-equals-vs-twice-equals/6 – Antony Hatchkins Dec 18 '11 at 9:55
1  
Using == still requires at least a type check - the interpreter can't compare the two operands without knowing their type first. – Alnitak Aug 13 '12 at 15:12
== is one less character than === :) – svidgen Jun 28 at 14:54

The issue boils down to three cases:

  1. The object has the property and its value is not undefined.
  2. The object has the property and its value is undefined.
  3. The object does not have the property.

This tells us something I consider important:

There is a difference between an undefined member and a defined member with an undefined value. But unhappily typeof obj.foo does not tell us which of the three cases we have. However we can combine this with "foo" in obj to distinguish the cases.

                               |  typeof obj.x === 'undefined' | !("x" in obj)
1.                   { "x"=1 } |  false                        | false
2.  { "x" = (function(){})() } |  true                         | false
3.                          {} |  true                         | true

I'd argue that in some cases it makes more sense (and is clearer) to check whether the property is there, than checking whether it is undefined.

For example: I've just been refactoring a bunch of code that had a bunch of checks whether an object had a given property.

if( typeof blob.x != 'undefined' ) {  fn(blob.x); }

Which was clearer when written without a check for undefined.

if( "x" in blob ) { fn(blob.x); }

But as has been mentioned these are not exactly the same (but are more than good enough for my needs).

share|improve this answer
4  
Hi Michael. Great suggestion, and I think it does make things cleaner. One gotcha that I found, however, is when using the ! operator with "in". You have to say if (!("x" in blob)) {} with brackets around the in, because the ! operator has precedence over 'in'. Hope that helps someone. – Simon Jun 15 '11 at 0:28
Sorry Michael, but this is incorrect, or at least misleading, in light of the original question. 'in' is not a sufficient way to test whether an object property has typeof undefined. For proof, please see this fiddle: jsfiddle.net/CsLKJ/4 – Tex Feb 25 '12 at 12:04
Those two code parts do a different thing! Consider and object given by a = {b: undefined}; then typeof a.b === typeof a.c === 'undefined' but 'b' in a and !('c' in a). – m_gol Sep 27 '12 at 14:07

if you do:

if(myvar == undefined )
 { alert('var does not exists or is not initialized'); }

It will fail when the var myvar does not exists because myvar is not defined, so the script is broken and the test has no effect.

Because the window object has a global scope (default object) outside a function, a declaration will be 'attached' to the window object.

for example:

var myvar = 'test';

the global var myvar is the same as window.myvar or window['myvar']

To avoid errors to test when a global variable exists, you better use:

if(window.myvar == undefined )
 { alert('var does not exists or is not initialized'); }

The question if a var really exists doesn't matter, it's value is incorrect. Otherwise, it is silly to initialize variables with undefined, better use the value false to initialize. When you know that all variables that you declare are initialized with false, you can simply check it's type or rely on !window.myvar to check if it has a proper/valid value. So even when the variable is not defined then !window.myvar is the same for myvar=undefined or myvar=false or myvar=0.

When you expect a specific type, test the type of the variable. To speed up testing a condition you better do:

if( !window.myvar || typeof window.myvar != 'string' )
 { alert('var does not exists or is not type of string'); }

When the first and simple condition is true, the interpreter skips next tests.

It is always better to use the instance/object of the variable to check if it got a valid value. It is more stable, a better way of programming.

Cheers!

Kind regards, Erwin Haantjes

share|improve this answer

You can get array all undefined with path using following code.

 function getAllUndefined(object) {

        function convertPath(arr, key) {
            var path = "";
            for (var i = 1; i < arr.length; i++) {

                path += arr[i] + "->";
            }
            path += key;
            return path;
        }


        var stack = [];
        var saveUndefined= [];
        function getUndefiend(obj, key) {

            var t = typeof obj;
            switch (t) {
                case "object":
                    if (t === null) {
                        return false;
                    }
                    break;
                case "string":
                case "number":
                case "boolean":
                case "null":
                    return false;
                default:
                    return true;
            }
            stack.push(key);
            for (k in obj) {
                if (obj.hasOwnProperty(k)) {
                    v = getUndefiend(obj[k], k);
                    if (v) {
                        saveUndefined.push(convertPath(stack, k));
                    }
                }
            }
            stack.pop();

        }

        getUndefiend({
            "": object
        }, "");
        return saveUndefined;     
    }

jsFiddle link

share|improve this answer
While it won't affect the validity of your code, you've got a typo: getUndefiend should be getUndefined. – icktoofay May 14 at 3:02

Object.hasOwnProperty(o, 'propertyname');

This doesn't look up through the prototype chain, however.

share|improve this answer
Object.hasOwnProperty won't work as expected; it checks if the Object object has a property with the name contained in o. You probably mean Object.prototype.hasOwnProperty.call(o, 'propertyname'). – icktoofay May 14 at 2:59

I didn't see (hope I didn't miss it) anyone checking the object before the property. So, this is the shortest and most effective (though not necessarily the most clear):

if (obj && obj.prop) {
  // Do something;
}

If the obj or obj.prop is undefined, null, or "falsy", the if statement will not execute the code block. This is usually the desired behavior in most code block statements (in JavaScript).

share|improve this answer
2  
If you want to know why this works: Javascript: Logical Operators and truthy / falsy – mb21 Feb 4 at 16:57

Crossposting my answer from related question How to check for "undefined" in JavaScript?

Specific to this question, see test cases with someObject.<whatever>.


Some scenarios illustrating the results of the various answers: http://jsfiddle.net/drzaus/UVjM4/

(Note that the use of var for in tests make a difference when in a scoped wrapper)

Code for reference:

(function(undefined) {
    var definedButNotInitialized;
    definedAndInitialized = 3;
    someObject = {
        firstProp: "1"
        , secondProp: false
        // , undefinedProp not defined
    }
    // var notDefined;

    var tests = [
        'definedButNotInitialized in window',
        'definedAndInitialized in window',
        'someObject.firstProp in window',
        'someObject.secondProp in window',
        'someObject.undefinedProp in window',
        'notDefined in window',

        '"definedButNotInitialized" in window',
        '"definedAndInitialized" in window',
        '"someObject.firstProp" in window',
        '"someObject.secondProp" in window',
        '"someObject.undefinedProp" in window',
        '"notDefined" in window',

        'typeof definedButNotInitialized == "undefined"',
        'typeof definedButNotInitialized === typeof undefined',
        'definedButNotInitialized === undefined',
        '! definedButNotInitialized',
        '!! definedButNotInitialized',

        'typeof definedAndInitialized == "undefined"',
        'typeof definedAndInitialized === typeof undefined',
        'definedAndInitialized === undefined',
        '! definedAndInitialized',
        '!! definedAndInitialized',

        'typeof someObject.firstProp == "undefined"',
        'typeof someObject.firstProp === typeof undefined',
        'someObject.firstProp === undefined',
        '! someObject.firstProp',
        '!! someObject.firstProp',

        'typeof someObject.secondProp == "undefined"',
        'typeof someObject.secondProp === typeof undefined',
        'someObject.secondProp === undefined',
        '! someObject.secondProp',
        '!! someObject.secondProp',

        'typeof someObject.undefinedProp == "undefined"',
        'typeof someObject.undefinedProp === typeof undefined',
        'someObject.undefinedProp === undefined',
        '! someObject.undefinedProp',
        '!! someObject.undefinedProp',

        'typeof notDefined == "undefined"',
        'typeof notDefined === typeof undefined',
        'notDefined === undefined',
        '! notDefined',
        '!! notDefined'
    ];

    var output = document.getElementById('results');
    var result = '';
    for(var t in tests) {
        if( !tests.hasOwnProperty(t) ) continue; // bleh

        try {
            result = eval(tests[t]);
        } catch(ex) {
            result = 'Exception--' + ex;
        }
        console.log(tests[t], result);
        output.innerHTML += "\n" + tests[t] + ": " + result;
    }
})();

And results:

definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined
share|improve this answer

protected by Starx Apr 25 '12 at 8:45

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

Not the answer you're looking for? Browse other questions tagged or ask your own question.