Home Detecting an undefined object property

# Detecting an undefined object property

Matt Sheppard
1#
Matt Sheppard Published in 2008-08-26 07:25:08Z
 What's the best way of checking if an object property in JavaScript is undefined?
Jamie Barker
2#
Jamie Barker Reply to 2017-08-01 09:03:37Z
 Use: if (typeof something === "undefined") { alert("something is undefined"); }  If an object variable which have some properties you can use same thing like this: if (typeof my_obj.someproperties === "undefined"){ console.log('the property is not available...'); // print into console } 
tslocum
3#
 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'); } 
Pandincus
4#
 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 
Peter Mortensen
5#
Peter Mortensen Reply to 2014-11-09 12:07:51Z
 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...
Simon East
6#
Simon East Reply to 2011-06-15 01:43:29Z
 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 } 
Peter Ajtai
7#
Peter Ajtai Reply to 2010-09-01 21:49:28Z
 if ( typeof( something ) == "undefined")  This worked for me while the others didn't.
Dave Jarvis
8#
Dave Jarvis Reply to 2017-08-15 20:52:27Z

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.

# Correct Code

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.

# Degenerate code. DO NOT USE.

var undefined = false;  // Shockingly, this is completely legal!
if (myVar === undefined) {
alert("You have been misled. Run away!");
}


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

Simon East
9#
Simon East Reply to 2011-06-29 07:21:12Z
 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 
Michael Anderson
10#
Michael Anderson Reply to 2014-01-30 02:49:19Z
 The issue boils down to three cases: The object has the property and its value is not undefined. The object has the property and its value is undefined. 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  Its worth noting that these tests are the same for null entries too  | typeof obj.x === 'undefined' | !("x" in obj) { x:null } | false | false  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, and the only case where this check will be different is case 2, the rare case of an actual entry in the object with an undefined value. 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).
Codebeat
11#
 If you do if (myvar == undefined ) { alert('var does not exists or is not initialized'); }  it will fail when the variable 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 variable 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 variable really exists doesn't matter, its value is incorrect. Otherwise, it is silly to initialize variables with undefined, and it is better use the value false to initialize. When you know that all variables that you declare are initialized with false, you can simply check its 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 the 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 and is a better way of programming. (y)
Peter Mortensen
12#
Peter Mortensen Reply to 2014-11-09 12:16:32Z
 You can get an array all undefined with path using the 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
Corey Richardson
13#
Corey Richardson Reply to 2012-02-18 16:26:44Z
 Object.hasOwnProperty(o, 'propertyname'); This doesn't look up through the prototype chain, however.
Joe Johnson
14#
Joe Johnson Reply to 2013-02-05 18:39:25Z
 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).
Community
15#
 Crossposting my answer from related question How to check for "undefined" in JavaScript? Specific to this question, see test cases with someObject.. 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 
Konstantin Smolyanin
16#
Konstantin Smolyanin Reply to 2015-09-26 19:01:06Z

What does this mean: "undefined object property"?

Actually it can mean two quite different things! First, it can mean the property that has never been defined in the object and, second, it can mean the property that has an undefined value. Let's look at this code:

var o = { a: undefined }


Is o.a undefined? Yes! Its value is undefined. Is o.b undefined? Sure! There is no property 'b' at all! OK, see now how different approaches behave in both situations:

typeof o.a == 'undefined' // true
typeof o.b == 'undefined' // true
o.a === undefined // true
o.b === undefined // true
'a' in o // true
'b' in o // false


We can clearly see that typeof obj.prop == 'undefined' and obj.prop === undefined are equivalent, and they do not distinguish those different situations. And 'prop' in obj can detect the situation when a property hasn't been defined at all and doesn't pay attention to the property value which may be undefined.

## So what to do?

1) You want to know if a property is undefined by either the first or second meaning (the most typical situation).

obj.prop === undefined // IMHO, see "final fight" below


2) You want to just know if object has some property and don't care about its value.

'prop' in obj


## Notes:

• You can't check an object and its property at the same time. For example, this x.a === undefined or this typeof x.a == 'undefined' raises ReferenceError: x is not defined if x is not defined.
• Variable undefined is a global variable (so actually it is window.undefined in browsers). It has been supported since ECMAScript 1st Edition and since ECMAScript 5 it is read only. So in modern browsers it can't be redefined to true as many authors love to frighten us with, but this is still a true for older browsers.

## Final fight: obj.prop === undefined vs typeof obj.prop == 'undefined'

Pluses of obj.prop === undefined:

• It's a bit shorter and looks a bit prettier
• The JavaScript engine will give you an error if you have misspelled undefined

Minuses of obj.prop === undefined:

• undefined can be overridden in old browsers

Pluses of typeof obj.prop == 'undefined':

• It is really universal! It works in new and old browsers.

Minuses of typeof obj.prop == 'undefined':

• 'undefned' (misspelled) here is just a string constant, so the JavaScript engine can't help you if you have misspelled it like I just did.

## Update (for server-side JavaScript):

Node.js supports the global variable undefined as global.undefined (it can also be used without the 'global' prefix). I don't know about other implementations of server-side JavaScript.

Fred
17#
 Here is my situation: I am using the result of a REST call. The result should be parsed from JSON to a JavaScript object. There is one error I need to defend. If the args to the rest call were incorrect as far as the user specifying the args wrong, the rest call comes back basically empty. While using this post to help me defend against this, I tried this. if( typeof restResult.data[0] === "undefined" ) { throw "Some error"; }  For my situation, if restResult.data[0] === "object", then I can safely start inspecting the rest of the members. If undefined then throw the error as above. What I am saying is that for my situation, all the suggestions above in this post did not work. I'm not saying I'm right and everyone is wrong. I am not a JavaScript master at all, but hopefully this will help someone.
Peter Mortensen
18#
Peter Mortensen Reply to 2014-11-09 12:22:26Z
 In the article Exploring the Abyss of Null and Undefined in JavaScript I read that frameworks like Underscore.js use this function: function isUndefined(obj){ return obj === void 0; } 
bevacqua
19#
 Compare with void 0, for terseness. if (foo !== void 0)  It's not as verbose as if (typeof foo !== 'undefined')
Peter Mortensen
20#
Peter Mortensen Reply to 2014-11-23 13:19:20Z

## 'if (window.x) { }' is error safe

Most likely you want if (window.x). This check is safe even if x hasn't been declared (var x;) - browser doesn't throw an error.

## Example: I want to know if my browser supports History API

if (window.history) {
history.call_some_function();
}


## How this works:

window is an object which holds all global variables as its members, and it is legal to try to access a non-existing member. If x hasn't been declared or hasn't been set then window.x returns undefined. undefined leads to false when if() evaluates it.

Ryan
21#
 Despite being vehemently recommended by many other answers here, typeof is a bad choice. It should never be used for checking whether variables have the value undefined, because it acts as a combined check for the value undefined and for whether a variable exists. In the vast majority of cases, you know when a variable exists, and typeof will just introduce the potential for a silent failure if you make a typo in the variable name or in the string literal 'undefined'. var snapshot = …; if (typeof snaposhot === 'undefined') { // ^ // misspelled¹ – this will never run, but it won’t throw an error! }  var foo = …; if (typeof foo === 'undefned') { // ^ // misspelled – this will never run, but it won’t throw an error! }  So unless you’re doing feature detection², where there’s uncertainty whether a given name will be in scope (like checking typeof module !== 'undefined' as a step in code specific to a CommonJS environment), typeof is a harmful choice when used on a variable, and the correct option is to compare the value directly: var foo = …; if (foo === undefined) { ⋮ }  Some common misconceptions about this include: that reading an “uninitialized” variable (var foo) or parameter (function bar(foo) { … }, called as bar()) will fail. This is simply not true – variables without explicit initialization and parameters that weren’t given values always become undefined, and are always in scope. that undefined can be overwritten. There’s a lot more to this. undefined is not a keyword in JavaScript. Instead, it’s a property on the global object with the Undefined value. However, since ES5, this property has been read-only and non-configurable. No modern browser will allow the undefined property to be changed, and as of 2017 this has been the case for a long time. Lack of strict mode doesn’t affect undefined’s behaviour either – it just makes statements like undefined = 5 do nothing instead of throwing. Since it isn’t a keyword, though, you can declare variables with the name undefined, and those variables could be changed, making this once-common pattern: (function (undefined) { // … })()  more dangerous than using the global undefined. If you have to be ES3-compatible, replace undefined with void 0 – don’t resort to typeof. (void has always been a unary operator that evaluates to the Undefined value for any operand.) With how variables work out of the way, it’s time to address the actual question: object properties. There is no reason to ever use typeof for object properties. The earlier exception regarding feature detection doesn’t apply here – typeof only has special behaviour on variables, and expressions that reference object properties are not variables. This: if (typeof foo.bar === 'undefined') { ⋮ }  is always exactly equivalent to this³: if (foo.bar === undefined) { ⋮ }  and taking into account the advice above, to avoid confusing readers as to why you’re using typeof, because it makes the most sense to use === to check for equality, because it could be refactored to checking a variable’s value later, and because it just plain looks better, you should always use === undefined³ here as well. Something else to consider when it comes to object properties is whether you really want to check for undefined at all. A given property name can be absent on an object (producing the value undefined when read), present on the object itself with the value undefined, present on the object’s prototype with the value undefined, or present on either of those with a non-undefined value. 'key' in obj will tell you whether a key is anywhere on an object’s prototype chain, and Object.prototype.hasOwnProperty.call(obj, 'key') will tell you whether it’s directly on the object. I won’t go into detail in this answer about prototypes and using objects as string-keyed maps, though, because it’s mostly intended to counter all the bad advice in other answers irrespective of the possible interpretations of the original question. Read up on object prototypes on MDN for more! ¹ unusual choice of example variable name? this is real dead code from the NoScript extension for Firefox. ² don’t assume that not knowing what’s in scope is okay in general, though. bonus vulnerability caused by abuse of dynamic scope: Project Zero 1225 ³ once again assuming an ES5+ environment and that undefined refers to the undefined property of the global object. substitute void 0 otherwise.
sam
22#
 "propertyName" in obj //-> true | false 
23#
 Also same things can be written shorter: if (!variable){ //do it if variable is Undefined }  or if (variable){ //do it if variable is Defined } 
Juan Garcia
24#
Juan Garcia Reply to 2014-06-18 06:14:25Z
 All the answers are incomplete. This is the right way of knowing that there is a property 'defined as undefined' : var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){ return ((prop in obj) && (typeof obj[prop] == 'undefined')) ; } ;  Example: var a = { b : 1, e : null } ; a.c = a.d ; hasUndefinedProperty(a, 'b') ; // false : b is defined as 1 hasUndefinedProperty(a, 'c') ; // true : c is defined as undefined hasUndefinedProperty(a, 'd') ; // false : d is undefined hasUndefinedProperty(a, 'e') ; // false : e is defined as null // And now... delete a.c ; hasUndefinedProperty(a, 'c') ; // false : c is undefined  Too bad that this been the right answer is buried in wrong answers >_< So, for anyone who pass by, I will give you undefineds for free!! var undefined ; undefined ; // undefined ({}).a ; // undefined [].a ; // undefined ''.a ; // undefined (function(){}()) ; // undefined void(0) ; // undefined eval() ; // undefined 1..a ; // undefined /a/.a ; // undefined (true).a ; // undefined 
Peter Mortensen
25#
Peter Mortensen Reply to 2014-11-09 12:26:12Z
 Going through the comments, for those who want to check both is it undefined or its value is null: //Just in JavaScript var s; // Undefined if (typeof s == "undefined" || s === null){ alert('either it is undefined or value is null') }  If you are using jQuery Library then jQuery.isEmptyObject() will suffice for both cases, var s; // Undefined jQuery.isEmptyObject(s); // Will return true; s = null; // Defined as null jQuery.isEmptyObject(s); // Will return true; //Usage if (jQuery.isEmptyObject(s)) { alert('Either variable:s is undefined or its value is null'); } else { alert('variable:s has value ' + s); } s = 'something'; // Defined with some value jQuery.isEmptyObject(s); // Will return false; 
Peter Mortensen
26#
Peter Mortensen Reply to 2014-11-09 12:27:35Z
 I would like to show you something I'm using in order to protect the undefined variable: Object.defineProperty(window, 'undefined', {});  This forbids anyone to change the window.undefined value therefore destroying the code based on that variable. If using "use strict", anything trying to change its value will end in error, otherwise it would be silently ignored.
Vitalii Fedorenko
27#
Vitalii Fedorenko Reply to 2014-12-14 22:35:24Z
 If you are using Angular: angular.isUndefined(obj) angular.isUndefined(obj.prop)  Underscore.js: _.isUndefined(obj) _.isUndefined(obj.prop) 
28#
 if simple typeof is not working try this one it will help: if(jQuery.type(variable) === "undefined") {// do something} 
Travis
29#

Reading through this, I'm amazed I didn't see this. I have found multiple algorithms that would work for this.

# Never Defined

If the value of an object was never defined, this will prevent from returning true if it is defined as null or undefined. This is helpful if you want true to be returned for values set as undefined

if(obj.prop === void 0) console.log("The value has never been defined");


# Defined as undefined Or never Defined

If you want it to result as true for values defined with the value of undefined, or never defined, you can simply use === undefined

if(obj.prop === undefined) console.log("The value is defined as undefined, or never defined");


# Defined as a falsy value, undefined,null, or never defined.

Commonly, people have asked me for an algorithm to figure out if a value is either falsy, undefined, or null. The following works.

if(obj.prop == false || obj.prop === null || obj.prop === undefined) {
console.log("The value is falsy, null, or undefined");
}

Community
30#
 I use if (this.variable) to test if it is defined. Simple if (variable), recommended above, fails for me. It turns out that it works only when variable is a field of some object, obj.someField to check if it is defined in the dictionary. But we can use this or window as the dictionary object since any variable is a field in current window, as I understand it. Therefore here is a test if (this.abc) alert("defined"); else alert("undefined"); abc = "abc"; if (this.abc) alert("defined"); else alert("undefined"); It first detects that variable abc is undefined and it is defined after initialization.
 Use: To check if property is undefined: if (typeof something === "undefined") { alert("undefined"); }  To check if property is not undefined: if (typeof something !== "undefined") { alert("not undefined"); }